JAVA No Reverse Solution


  • 0
    public List<Integer> postorderTraversal(TreeNode root) {
        Stack<TreeNode> st=new Stack<>();
        List<Integer> ans=new ArrayList<>();
        if(root==null) return ans;
        st.push(root);
        TreeNode pre=root;
        TreeNode cur=root;
        while(!st.isEmpty())
        {
            pre=cur;
            cur=st.peek();
            if((cur.left!=null||cur.right!=null)&&(pre!=cur.left&&pre!=cur.right))
            {
                if(cur.right!=null) st.push(cur.right);
                if(cur.left!=null)  st.push(cur.left);
            }
            else
            {
                ans.add(st.pop().val);
            }
        }
        return ans;
    }

Log in to reply
 

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