您的位置:首页 > 其它

lintcode二叉树的层次遍历||

2018-03-14 13:17 134 查看

题目:

给出一棵二叉树,返回其节点值从底向上的层次序遍历(按从叶节点所在层到根节点所在的层遍历,然后逐层从左往右遍历)

样例:

给出一棵二叉树 {3,9,20,15,7},

3

/ \

9 20

/ \

15 7

按照从下往上的层次遍历为:

[

[15,7],

[9,20],

[3]

]

答案:

public List<List<Integer>> levelOrderBottom(TreeNode root) {
// write your code here
List<List<Integer>> result = new LinkedList<List<Integer>>();
if(root==null)
return result;
Queue<TreeNode> q = new LinkedList<TreeNode>();
q.offer(root);
while(!q.isEmpty()){

4000
Queue<TreeNode> temp = new LinkedList<TreeNode>();
List<Integer> l = new LinkedList<Integer>();
while(!q.isEmpty()){
TreeNode t = q.poll();
l.add(t.val);
if(t.left!=null)
temp.offer(t.left);
if(t.right!=null)
temp.offer(t.right);
}
result.add(l);
q = temp;
}

Collections.reverse(result);
return result;

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: