Binary Tree Postorder Traversal

 1 public class Solution {
 2     public ArrayList<Integer> postorderTraversal(TreeNode root) {
 3         ArrayList<Integer> res = new ArrayList<Integer>();
 4         if(root==null) return res;
 5         TreeNode cur = null, pre = null;
 6         Stack<TreeNode>stack = new Stack<TreeNode>();
 7         stack.push(root);
 8         while(!stack.isEmpty()){
 9             cur = stack.peek();
10             if((cur.right==null && cur.left==null) ||(pre!=null && (cur.right==pre || cur.left==pre))){
11                 res.add(cur.val);
12                 pre = cur;
13                 stack.pop();
14             }else{
15                 if(cur.right!=null){
16                     stack.push(cur.right);
17                 }
18                 if(cur.left!=null){
19                     stack.push(cur.left);
20                 }
21             }
22         }
23         return res;
24     }
25 }
View Code

 

posted @ 2014-02-19 05:25  krunning  阅读(204)  评论(0编辑  收藏  举报