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; }
相关文章推荐
- lintcode二叉树的锯齿形层次遍历 (双端队列)
- lintcode二叉树的层次遍历
- 第十周 项目一 层次遍历算法的验证
- lintcode&九章算法——No.70 二叉树的层次遍历(二) ? 待解决
- 数据结构(六)——二叉树 前序、中序、后序、层次遍历及非递归实现 查找、统计个数、比较、求深度的递归实现
- 二叉树层次遍历的应用--改造二叉链表
- 中序遍历,层次遍历构建二叉树
- 数据结构实验之求二叉树后序遍历和层次遍历
- 数据结构实验之求二叉树后序遍历和层次遍历
- 二叉树的层次遍历(广度优先遍历)
- 树的孩子链表表示法可执行代码(创建,层次遍历)
- 二叉树的层次遍历
- 层次遍历 二叉树
- 二叉树的层次遍历指针方法
- 寒假训练--树与二叉树--数据结构实验之求二叉树后序遍历和层次遍历
- 多叉数层次遍历
- 二叉树的层次遍历
- 二叉树的锯齿形层次遍历
- 非递归算法实现树的先序遍历,中序遍历,后序遍历;也有树的层次遍历。
- 【二叉树层次遍历】Binary Tree Level Order Traversal