Java solution without reversing from preorder traversal


  • 0
    X

    Most of solutions are adapted from preorder traversal, but this method can output the result directly instead of reversing the sequence. It is similar to the two stack method, but I used a hash set here to store the appearance of each node. Hope it can help~

        public List<Integer> postorderTraversal(TreeNode root) {
            List<Integer> list = new ArrayList<>();
            if (root == null) return list;
            
            HashSet<TreeNode> set = new HashSet<>();
            Stack<TreeNode> stack = new Stack<>();
            stack.push(root);
            
            while (!stack.isEmpty()) {
                TreeNode top = stack.peek();
                if (!set.contains(top)) {
                    if (top.right != null) stack.push(top.right);
                    if (top.left != null) stack.push(top.left);
                    set.add(top);
                } else {
                    list.add(top.val);
                    stack.pop();
                }
            }
            return list;
        }
    

Log in to reply
 

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