Binary Tree postorder Traversal
Given a binary tree, return the postorder traversal of its nodes ' values.
Given binary Tree
{1,#,2,3},
1 2 / 3
Return [3,2,1] .
Challenge
Can do it without recursion?
Among preorder,inorder and postorder binary tree traversal problems, postorder traversal is the most complicated one.
Analysis
The key to iterative Postorder traversal is the following:
- The order of "Postorder" is:left Child, right child, parent node.
- Find the relation between the previously visited node and the current node
- Use a stack to track nodes
As we go down the tree to the LFT, check the previously visited node. If The current node was the left or right child of the previous node, then keep going down the tree, and add left/right nod E to stack when applicable. When there was no children for current node, i.e., the current node was a leaf, pop it from the stack. Then the previous node become to is under the current node for Next loop. You can using a example to walk through the code.
/*** Definition of TreeNode: * public class TreeNode {* public int val; * Public TreeNode left, right; * PU Blic TreeNode (int val) {* This.val = val; * This.left = This.right = null; *} *}*/ Public classSolution {/** * @paramroot:the root of binary tree. * @return: Postorder in ArrayList which contains node values. */ PublicArraylist<integer>postordertraversal (TreeNode root) {//Write your code hereArraylist<integer> list=NewArraylist<integer>(); if(root==NULL)returnlist; Stack<TreeNode> stack=NewStack<treenode>(); Stack.push (root); TreeNode prev=NULL; while(!Stack.empty ()) { //go down the tree. //Check if current node was leaf, if so, process it and pop stack,//Otherwise, keep going downTreeNode cur=Stack.peek (); if(prev==NULL|| prev.left==cur| | prev.right==cur) { if(cur.left!=NULL) {Stack.push (cur.left); } Else if(cur.right!=NULL) {Stack.push (cur.right); } Else{stack.pop (); List.add (Cur.val); } } //go up the tree from left node//need to check if there//If yes, push it to stack//Otherwise, process parent and pop stack Else if(cur.left==prev) { if(cur.right!=NULL) {Stack.push (cur.right); } Else{stack.pop (); List.add (Cur.val); } } //go up the tree from right node//After coming back from the right node, process parent node and pop stack. Else if(cur.right==prev) {Stack.pop (); List.add (Cur.val); } prev=cur; } returnlist; }}
Article Source: http://www.programcreek.com/2012/12/leetcode-solution-of-binary-tree-inorder-traversal-in-java/
[Lintcode Easy] Binary Tree postorder Traversal