LeetCode——111. Minimum Depth of Binary Tree
来源:互联网 发布:淘宝买dota2饰品 编辑:程序博客网 时间:2024/05/01 11:42
问题描述:
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).For example:Given binary tree [3,9,20,null,null,15,7], 3 / \9 20 / \ 15 7return its level order traversal as:[ [15,7], [9,20], [3]]
这道题大致的意思就是从下到上遍历二叉树,将每一层的节点存入一个list中,最后将每一层的list存入到一个总的list中。
这道题实际上跟上一题几乎一模一样。
Binary Tree Level Order Traversal
从结果来看,这一题与上一题不同的地方就在最后结果的排列顺序,上一题是从上往下,这一题是从下往上,那么我们只要在将tempList插入到result时改变顺序,将它插入到result的头部,就可以实现逆序了。所以如果上一题做出来的话,这一题没有太大的问题。我就不细讲了。
直接上代码吧:
public List<List<Integer>> levelOrderBottom(TreeNode root) { if(root == null) return new LinkedList<List<Integer>>(); List<List<Integer>> result = new LinkedList<>(); Queue<TreeNode> tempQueue = new LinkedList<>(); tempQueue.offer(root); while(tempQueue.peek() != null) { List<Integer> tempList = new LinkedList<>(); int levelSize = tempQueue.size(); for(int i = 0; i < levelSize; i++) { //弹出节点 TreeNode tempNode = tempQueue.poll(); tempList.add(tempNode.val); //将他的左右节点添加进队列中 if(tempNode.left != null) tempQueue.offer(tempNode.left); if(tempNode.right != null) tempQueue.offer(tempNode.right); } //其实这一题与上一题不同的地方就是结果list中的顺序相反 //那么我们在插入的时候改变顺序,从头部插入,就可以改变最终的顺序 result.add(0, tempList); } return result;}
谢谢大家观看我的博客。如果有不明白的地方,或者是文中有错误的地方,欢迎指出,谢谢!
阅读全文
0 0
- LeetCode——111. Minimum Depth of Binary Tree
- LeetCode——111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- [LeetCode]111.Minimum Depth of Binary Tree
- 【LeetCode】111.Minimum Depth of Binary Tree
- [Leetcode] 111. Minimum Depth of Binary Tree
- [leetcode] 111. Minimum Depth of Binary Tree
- 111. Minimum Depth of Binary Tree LeetCode
- 【LeetCode】111. Minimum Depth of Binary Tree
- LeetCode *** 111. Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- leetcode-111. Minimum Depth of Binary Tree
- LeetCode-111.Minimum Depth of Binary Tree
- LeetCode 111.Minimum Depth of Binary Tree
- Leetcode 111. Minimum Depth of Binary Tree
- [leetcode]111.Minimum Depth of Binary Tree
- 111.[Leetcode]Minimum Depth of Binary Tree
- LeetCode 111. Minimum Depth of Binary Tree
- 嵌入式Linux入门12:应用层调试
- 线程--同步函数被static修饰锁是类名.class
- python操作Excel读写--使用xlrd
- 从ODX(Open diagnostic Data eXchange)谈车联网应用绕不开的底层网络“基建”
- Windows游戏开发(C++)
- LeetCode——111. Minimum Depth of Binary Tree
- 我的Ruby学习历程之初识数组
- 深入理解Java虚拟机——JVM的内存结构和内存分配策略
- int型32位压缩
- 通过代码关闭actionMode
- Python爬虫使用PyV8执行js代码
- 以太网帧格式、IP数据报格式、TCP段格式+UDP段格式 详解
- 【LeetCode】最短路径条数问题(BFS)
- 我的Ruby学习历程之初识Hash(杂凑)