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

从底向上层次遍历二叉树

时间:2016-03-24 13:05:02      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

题目原型:

 

Given a binary tree, return the bottom-up level order traversal of its nodes‘ values. (ie, from left to right, level by level from leaf to root).

For example:
Given binary tree {3,9,20,#,#,15,7},

1
2
3
4
5
  3
 / \
9  20
  /  \
 15   7

 

return its bottom-up level order traversal as:

1
2
3
4
5
[
  [15,7]
  [9,20],
  [3],
]

基本思路:

由于是从底向上,所以用到了栈。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
public ArrayList> levelOrderBottom(TreeNode root)
{
    Stack> stack = new Stack>();
    ArrayList> list = new ArrayList>();
    ArrayList<TREENODE> nodeSet = new ArrayList<TREENODE>();
    ArrayList<TREENODE> tmp ;
    ArrayList<INTEGER> numSet ;
    if(root!=null)
    {
        nodeSet.add(root);
        while(nodeSet.size()>0)
        {
            tmp = new ArrayList<TREENODE>();
            numSet = new ArrayList<INTEGER>();
            //添加到stack中
            for(TreeNode tn : nodeSet)
                numSet.add(tn.val);
              
            //添加到stack中
            stack.push(numSet);
              
            //求下一层的节点
            for(TreeNode it : nodeSet)
            {
                if(it.left!=null)
                    tmp.add(it.left);
                if(it.right!=null)
                    tmp.add(it.right);
            }
            nodeSet = tmp;
        }
          
        //添加到list中
        while(stack.size()>0)
        {
            ArrayList<INTEGER> rs = stack.pop();
            list.add(rs);
        }
    }
    return list;
}



 

从底向上层次遍历二叉树

标签:

原文地址:http://www.cnblogs.com/firstdream/p/5315018.html

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