Can anyone tell me what is wrong with this java code?


  • 0
    M

    The answer was wrong as this:
    Input: {3,1,2}
    Output: [3,1]
    Expected [3,1,2]

    code:

        public List<Integer>  preorderTraversal(TreeNode root) {
        List ans = new ArrayList();
        if(root == null) return ans;
        ans.add(root.val);
        Stack<TreeNode> st= new Stack<TreeNode>();
        TreeNode tmp;
        st.push(root);
    
        while(!st.isEmpty()) {
            tmp = st.pop();
            if (tmp.left != null) {
                st.push(tmp.left);
                ans.add(tmp.left.val);
                tmp.left = null;
                continue;
            }
            if (tmp.right != null) {
                st.push(tmp.right);
                ans.add(tmp.right.val);
                tmp.right = null;
                continue;
            }
    
        }
        return ans;
        
    }

  • 0
    M

    Just put a st.push(tmp) after the first if then everything is ok.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.