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 do it iteratively?
Show Tags
Has you met this question in a real interview? Yes No
Discuss
Solution 1:
Recursive solution
1 PublicList<integer>postorderTraversal1 (TreeNode root) {2list<integer> ret =NewArraylist<integer>();3 Dfs (root, ret);4 returnret;5 }6 7 //Solution 1:rec8 Public voidDFS (TreeNode root, list<integer>ret) {9 if(Root = =NULL) {Ten return; One } A - Dfs (Root.left, ret); - Dfs (root.right, ret); the Ret.add (root.val); -}View Code
Solution 2:
/**
* Sequential Traversal iterative method
* Http://www.youtube.com/watch?v=hv-mJUs5mvU
* http://blog.csdn.net/tang_jin2015/article/details/8545457
* Sequence from left to right is the same as the reverse order from right to left, so it's easy! Ha ha
* Flip with another stack
*/
1 //Solution 2:iterator2 PublicList<integer>postordertraversal (TreeNode root) {3list<integer> ret =NewArraylist<integer>();4 if(Root = =NULL) {5 returnret;6 }7 8stack<treenode> s =NewStack<treenode>();9Stack<integer> out =NewStack<integer>();Ten One S.push (root); A - while(!S.isempty ()) { -TreeNode cur =S.pop (); the Out.push (cur.val); - - if(Cur.left! =NULL) { - S.push (cur.left); + } - + if(Cur.right! =NULL) { A S.push (cur.right); at } - } - - while(!Out.isempty ()) { - Ret.add (Out.pop ()); - } in - returnret; to}View Code
GITHUB:
Https://github.com/yuzhangcmu/LeetCode_algorithm/blob/master/tree/PostorderTraversal.java
Leetcode:binary Tree postorder Traversal Problem Solving report