Java Iterative PostOrderTraversal


  • 0
    A
    public List<Integer> postorderTraversal(TreeNode root) {
            Stack<TreeNode> stack = new Stack<>();
            Stack<TreeNode> stackFinal = new Stack<>();
            if(root != null) {
                stack.add(root);
            }
            while(!stack.isEmpty()) {
                root = stack.pop();
                stackFinal.add(root);
                if(root.left != null)
                    stack.add(root.left);
                if(root.right != null)
                    stack.add(root.right);
            }
            
            List<Integer> list = new ArrayList<>();
            while(!stackFinal.isEmpty()) {
                list.add(stackFinal.pop().val);
            }
            return list;
        }
    

Log in to reply
 

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