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,null,null,15,7],

    3
/ \
9 20
/ \
15 7

return its bottom-up level order traversal as:

[
[15,7],
[9,20],
[3]
] Solution 1:
BFS
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> arrList = new ArrayList<>();
if (root == null) {
return arrList;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < size; i++) {
TreeNode cur = queue.poll();
list.add(cur.val);
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
arrList.add(0, list);
}
return arrList;
}
}

Solution 2:

/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
List<List<Integer>> arrList = new ArrayList<>();
helper(arrList, 0, root);
return arrList;
} private void helper(List<List<Integer>> res, int depth, TreeNode root) {
if (root == null) {
return;
}
// backtrack case, resSize >= depth
if (depth >= res.size()) {
res.add(0, new LinkedList<>());
}
res.get(res.size() - 1 - depth).add(root.val);
helper(res, depth + 1, root.left);
helper(res, depth + 1, root.right);
}
}

最新文章

  1. 简单搭建 nuget 内部服务器
  2. .NET 基础一步步一幕幕[面向对象前言]
  3. H5移动前端开发常用高能css3汇总
  4. python 多线程threading
  5. [转]ubuntu 下minicom超级终端的使用方法
  6. UESTC_How many good substrings CDOJ 1026
  7. ListView的使用——聊天窗口
  8. cocos2d 游戏开发实战
  9. Android实现Excel表格,且表格能左右、上下滑动
  10. Java 开发中如何正确踩坑
  11. 浅入深出之Java集合框架(下)
  12. RESTful 的总结
  13. httpservlet里单纯分页
  14. python简单名片管理系统
  15. lis最长上升子序列
  16. Git工作流程最佳实践总结
  17. PAT 1081 检查密码(15) (代码+思路)
  18. mysql修改Truncated incorrect DOUBLE value:
  19. 20145305 《网络对抗》Web安全基础实践
  20. Package libvirt was not found in the pkg-config search path

热门文章

  1. Javascript object.constructor属性与面向对象编程(oop)
  2. webservice wsdl文件标签讲解
  3. UVALive 6491 You win! 状态DP
  4. JNI传递修改自定义Java Class数组数据
  5. [CF百场计划]#2 Codeforces Round #618 (Div. 2)
  6. 干货分享,FPGA硬件系统的设计技巧
  7. PyCharm 代码行出现多余的数字
  8. vue-router中参数传递
  9. 题解 P6005 【[USACO20JAN]Time is Mooney G】
  10. blocking(非阻塞)回调函数