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?

[解题思路]

后序遍历的非递归相对来说比较难,根节点需要在其左右孩子都访问结束后才能被访问,因此对于任一节点,先将其入栈,如果p不存在左孩子和右孩子,则可以直接访问它;或者p存在左孩子或者右孩子,但是其左孩子和右孩子都已被访问过了,则同样可以直接访问该节点。若非上述两种情况,则将p的右孩子和左孩子依次入栈,这样就保证了每次去站定元素的时候,左孩子在右孩子前面被访问,左孩子和右孩子在根节点前面被访问。

 1 public ArrayList<Integer> postorderTraversal(TreeNode root) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         ArrayList<Integer> result = new ArrayList<Integer>();
 5         if(root == null){
 6             return result;
 7         }
 8         
 9         Stack<TreeNode> stack = new Stack<TreeNode>();
10         TreeNode cur = null, pre = null;
11         stack.push(root);
12         
13         while(!stack.empty()){
14             cur = stack.peek();
15             if((cur.left == null && cur.right == null) ||
16             ((pre != null) && (cur.left == pre || cur.right == pre))){
17                 result.add(cur.val);
18                 pre = cur;
19                 stack.pop();
20             } else {
21                 if(cur.right != null){
22                     stack.push(cur.right);
23                 }
24                 if(cur.left != null){
25                     stack.push(cur.left);
26                 }
27             }
28             
29         }
30         
31         return result;
32     }

 

你可能感兴趣的:(LeetCode)