LeetCode 102. Binary Tree Level Order Traversal
2016-04-20 15:35
211 查看
思路:这道题目感觉有点难度。题目的意思是将每一层的节点都放到一个list中,最后返回一个list
public List<List<Integer>> levelOrder(TreeNode root) { List<List<Integer>> answerList = new LinkedList<List<Integer>>(); // nodeList用来记录每一层的节点 List<Integer> nodeList = new ArrayList<Integer>(); //current用来记录遍历每一层节点时,用来表示当前的节点 LinkedList<TreeNode> current = new LinkedList<TreeNode>(); // next用来记录下一层的节点。 LinkedList<TreeNode> next = new LinkedList<TreeNode>(); if(root == null){ return answerList; } current.add(root); while(!current.isEmpty()){ // remove()是把top节点拿出来并在队列中删除,并将下层节点放到next中 TreeNode tr = current.remove(); if(tr.left != null){ next.add(tr.left); } if(tr.right != null){ next.add(tr.right); } nodeList.add(tr.val); // 当队列为空时,就把这一层的nodeList放到answerList中。 if(current.isEmpty()){ current = next; next = new LinkedList<TreeNode>(); answerList.add(nodeList); nodeList = new ArrayList<Integer>(); } } return answerList; }
相关文章推荐
- Android视图状态及重绘流程分析,带你一步步深入了解View(三)
- 使用jQuery+PHP+Mysql实现抽奖程序
- Windows键盘钩子
- 局部变量与实例变量---一道c#面试题想到的
- 【LeetCode-342】Power of Four
- 进程间8种通信方式详解
- 读书笔记—View的工作原理
- 常用端口号及对应服务
- java基础笔记之static
- 邮件被暴力破解邮件网关如何解决
- 全面解析Linux数字文件权限
- Android LruCache源码详解
- Redis+Spring缓存实例(windows环境)
- Python 解析base64数据到opencv图像
- 为什么必须是final的呢?
- NHB网络心跳丢失的模拟过程分析
- 模态跳转过后,依然有导航栏
- 第四周—求n的阶乘
- 『引』最全前端资源汇集。
- iOS 学习笔记七 【博爱手把手教你使用2016年gitHub Mac客户端】