码迷,mamicode.com
首页 > 其他好文 > 详细

Leetcode-Binary Tree Postorder Traversal

时间:2014-12-12 01:15:30      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:des   style   blog   io   ar   color   os   sp   for   

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?

Solution:

 1 /**
 2  * Definition for binary tree
 3  * public class TreeNode {
 4  *     int val;
 5  *     TreeNode left;
 6  *     TreeNode right;
 7  *     TreeNode(int x) { val = x; }
 8  * }
 9  */
10 public class Solution {
11     public List<Integer> postorderTraversal(TreeNode root) {
12         List<Integer> res = new ArrayList<Integer>();
13         if (root==null) return res;
14 
15         Stack<TreeNode> nStack = new Stack<TreeNode>();
16         Stack<Integer> record = new Stack<Integer>();
17         nStack.push(root);
18         record.push(0);
19 
20         while (nStack.size()!=0){
21             TreeNode cur = nStack.peek();
22             if (cur.left==null && cur.right==null){
23                 res.add(cur.val);
24                 nStack.pop();
25                 record.pop();
26                 continue;
27             }
28 
29             int val = record.peek();
30             if (val==0){
31                 record.pop();
32                 record.push(val+1);
33                 if (cur.left!=null){
34                     nStack.push(cur.left);
35                     record.push(0);
36                 }
37                 continue;
38             }
39 
40             if (val==1){
41                 record.pop();
42                 record.push(val+1);
43                 if (cur.right!=null){
44                     nStack.push(cur.right);
45                     record.push(0);
46                 }
47                 continue;
48             }
49 
50             if (val==2){
51                 res.add(cur.val);
52                 nStack.pop();
53                 record.pop();
54                 continue;
55             }
56         }
57 
58         return res;  
59         
60     }
61 }

 

Leetcode-Binary Tree Postorder Traversal

标签:des   style   blog   io   ar   color   os   sp   for   

原文地址:http://www.cnblogs.com/lishiblog/p/4158857.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!