Binary Tree Level Order Traversal II
2016-05-14 11:03
288 查看
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},
解题思路:
首先想到的是二叉树的层序遍历,此题有两个关注点,首先是如何用两个计数变量来确定二叉树每一层上子结点的个数,其次是Arraylist.add(0,templist)方法来实现倒序
算法如下:
For example:
Given binary tree {3,9,20,#,#,15,7},
3 / \ 9 20 / \ 15 7
return its bottom-up level order traversal as:
[ [15,7], [9,20], [3] ]
解题思路:
首先想到的是二叉树的层序遍历,此题有两个关注点,首先是如何用两个计数变量来确定二叉树每一层上子结点的个数,其次是Arraylist.add(0,templist)方法来实现倒序
算法如下:
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public List<List<Integer>> levelOrderBottom(TreeNode root) { List<List<Integer>> resultlist = new ArrayList<>(); if(root==null) return resultlist; List<Integer> templist = new ArrayList<Integer>(); LinkedList<TreeNode> s = new LinkedList<TreeNode>(); s.add(root); int curIndex = 1; int nextIndex = 0; while(!s.isEmpty()){ TreeNode node = s.poll(); curIndex--; templist.add(node.val); if(node.left!=null){ s.add(node.left); nextIndex++; } if(node.right!=null){ s.add(node.right); nextIndex++; } if(curIndex==0){ resultlist.add(0,templist); templist = new ArrayList<Integer>(); curIndex = nextIndex ; nextIndex = 0; } } return resultlist; } }
相关文章推荐
- Eclipse安装Maven插件
- 第10、11周项目2 存储班长信息的学生类
- app上传新版本后用户从appStore下载打开应用就闪退
- Codeforces 307 div2 E.GukiZ and GukiZiana 分块
- 营销型网站的8大策略
- 实现复数类中的运算符重载
- win下一些小工具
- unix编程(九)进程间通信
- APP开发实战14-APP开发人员所需知识
- jvm中分代垃圾回收和触发垃圾回收
- 如果四位数各位上的数字均是0或2或4或6或8,则统计出满足此条件的个数cnt,并把这些四位数按从大到小的顺序存入数组b中。(160514)
- 3518e 开启第三个串口uart2
- Linux之特殊权限(SUID/SGID/SBIT)
- 在 idea 中使用 gradle 导入maven仓库
- Android 编译ffmpeg
- java String.split()函数的用法分析
- iOS——UITableView的优化
- 手机开发实战14——GSM业务种类2
- 总结
- 常用的正则表达式