LeetCode: Binary Tree Postorder Traversal
Given a binary tree, return the postorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [3,2,1]
.
Note: Recursive solution is trivial, could you do it iteratively?
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public ArrayList<Integer> postorderTraversal(TreeNode root) { // IMPORTANT: Please reset any member data you declared, as // the same Solution instance will be reused for each test case. ArrayList<Integer> result = new ArrayList<Integer>(); Stack<TreeNode> stack = new Stack<TreeNode>(); if(root == null) return result ; stack.push(root); TreeNode prev = null; while(!stack.isEmpty()){ TreeNode curr = stack.peek(); // traverse down if(prev == null || curr == prev.left || curr == prev.right){ if(curr.left != null) stack.push(curr.left); else if(curr.right != null) stack.push(curr.right); }// traverse up else if(curr.left == prev){ if(curr.right != null) stack.push(curr.right); }else{ result.add(curr.val); stack.pop(); } prev = curr; } return result; } }