題目:
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?
題解:
遞迴方法程式碼:
2 if(root==null)
3 return;
4
5 helper(root.left,re);
6 helper(root.right,re);
7 re.add(root.val);
8 }
9 public ArrayList<Integer> postorderTraversal(TreeNode root) {
10 ArrayList<Integer> re = new ArrayList<Integer>();
11 if(root==null)
12 return re;
13 helper(root,re);
14 return re;
15 }
非遞迴方法程式碼:
引用自Code ganker:http://blog.csdn.net/linhuanmars/article/details/22009351
“接下來是迭代的做法,本質就是用一個棧來模擬遞迴的過程,但是相比於Binary
Tree Inorder Traversal和Binary
Tree Preorder Traversal,後序遍歷的情況就複雜多了。我們需要維護當前遍歷的cur指標和前一個遍歷的pre指標來追溯當前的情況(注意這裡是遍歷的指標,並不是真正按後序訪問順序的結點)。具體分為幾種情況:
(1)如果pre的左孩子或者右孩子是cur,那麼說明遍歷在往下走,按訪問順序繼續,即如果有左孩子,則是左孩子進棧,否則如果有右孩子,則是右孩子進棧,如果左右孩子都沒有,則說明該結點是葉子,可以直接訪問並把結點出棧了。
(2)如果反過來,cur的左孩子是pre,則說明已經在回溯往上走了,但是我們知道後序遍歷要左右孩子走完才可以訪問自己,所以這裡如果有右孩子還需要把右孩子進棧,否則說明已經到自己了,可以訪問並且出棧了。
(3)如果cur的右孩子是pre,那麼說明左右孩子都訪問結束了,可以輪到自己了,訪問並且出棧即可。
演算法時間複雜度也是O(n),空間複雜度是棧的大小O(logn)。實現的程式碼如下(程式碼引用自:http://www.programcreek.com/2012/12/leetcode-solution-of-iterative-binary-tree-postorder-traversal-in-java/):”
2
3 ArrayList<Integer> lst = new ArrayList<Integer>();
4
5 if(root == null)
6 return lst;
7
8 Stack<TreeNode> stack = new Stack<TreeNode>();
9 stack.push(root);
10
11 TreeNode prev = null;
12 while(!stack.empty()){
13 TreeNode curr = stack.peek();
14
15 // go down the tree.
16 //check if current node is leaf, if so, process it and pop stack,
17 //otherwise, keep going down
18 if(prev == null || prev.left == curr || prev.right == curr){
19 //prev == null is the situation for the root node
20 if(curr.left != null){
21 stack.push(curr.left);
22 }else if(curr.right != null){
23 stack.push(curr.right);
24 }else{
25 stack.pop();
26 lst.add(curr.val);
27 }
28
29 //go up the tree from left node
30 //need to check if there is a right child
31 //if yes, push it to stack
32 //otherwise, process parent and pop stack
33 }else if(curr.left == prev){
34 if(curr.right != null){
35 stack.push(curr.right);
36 }else{
37 stack.pop();
38 lst.add(curr.val);
39 }
40
41 //go up the tree from right node
42 //after coming back from right node, process parent node and pop stack.
43 }else if(curr.right == prev){
44 stack.pop();
45 lst.add(curr.val);
46 }
47
48 prev = curr;
49 }
50
51 return lst;
52 }