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) { ArrayList<Integer> result = new ArrayList<Integer>(); if(root != null){ Stack<TreeNode> sta = new Stack<TreeNode>(); sta.push(root); HashSet<TreeNode> hset = new HashSet<TreeNode>(); hset.add(root); while(!sta.empty()){ TreeNode aNode = sta.pop(); if(aNode.left != null && hset.add(aNode.left)){ sta.push(aNode); sta.push(aNode.left); } else if(aNode.right != null && hset.add(aNode.right)){ sta.push(aNode); sta.push(aNode.right); } else result.add(aNode.val); } } return result; } }
Another solution:
public class Solution { public List<Integer> postorderTraversal(TreeNode root) { List<Integer> postOrderTreeValue = new ArrayList<Integer>(); Stack<TreeNode> TreeNodeStack = new Stack<TreeNode>(); TreeNode haveDoneRightNode = null; //initialize the stack with TreeNodes if(root != null) putTreeNodeInStack(TreeNodeStack, root); while(!TreeNodeStack.isEmpty()){ TreeNode currentNode = TreeNodeStack.pop(); if(currentNode.right == null || currentNode.right == haveDoneRightNode){ postOrderTreeValue.add(currentNode.val); if(!TreeNodeStack.isEmpty() && currentNode == TreeNodeStack.peek().right) haveDoneRightNode = currentNode; } else{ TreeNodeStack.push(currentNode); putTreeNodeInStack(TreeNodeStack, currentNode.right); } } return postOrderTreeValue; } private void putTreeNodeInStack(Stack<TreeNode> TreeNodeStack, TreeNode root){ while(root !=null){ TreeNodeStack.push(root); if(root.left != null) root = root.left; else if(root.right != null) root = root.right; else root = null; } } }