Intuitive java solution


  • 0
    S
    public class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> res = new ArrayList<Integer>();
            TreeNode prev = root;
            if(root == null){
                return res;
            }
            Stack<TreeNode> s = new Stack<TreeNode>();
            s.push(root);
            while(!s.empty()){
                TreeNode ptr = s.peek();
                    
                    while(ptr.left!=null && ptr.left!=prev && ptr.right!=prev){
                        s.push(ptr.left);
                        ptr = ptr.left;
                    }
                    if(ptr.right!=null && ptr.right!=prev ){
                        s.push(ptr.right);
                        ptr = ptr.right;
                    } 
                    if((ptr.left==null && ptr.right == null) || ptr.right==prev || ptr.left == prev){
                        res.add(ptr.val);
                        s.pop();
                        prev = ptr;
                    }
                
               
            }
            return res;
        }
    }
    

Log in to reply
 

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