Java Iterative Solution without reverse


  • 0
    N
    public class Solution {
        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> result = new ArrayList<>();
            Deque<TreeNode> stack = new LinkedList<>();
            TreeNode lastVisited = null, peek = null, node = root;
            while(!stack.isEmpty() || node != null){
                if(node != null){
                    stack.offerFirst(node);
                    node = node.left;
                }
                else{
                    peek = stack.peekFirst();
                    if(peek.right != null && peek.right != lastVisited){
                        node = peek.right;
                    }
                    else{
                        result.add(peek.val);
                        lastVisited = stack.poll();
                    }
                }
            }
            return result;
        }
    }
    

Log in to reply
 

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