博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 102. Binary Tree Level Order Traversal
阅读量:4692 次
发布时间:2019-06-09

本文共 1366 字,大约阅读时间需要 4 分钟。

原题链接在这里:

题目:

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   7

return its level order traversal as:

[  [3],  [9,20],  [15,7]]

题解:

是一道BFS,利用queue,先进先出,并利用curCount来判断是否走完了当前一层。当curCount = 0 时表示当前一层走完,要把当前list加入res里,再刷新list,问题是不要忘记同时刷新curCount和nextCount.

Time Complexity: O(n). Space: O(n).

AC Java:

/** * 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
> levelOrder(TreeNode root) { List
> res = new ArrayList
>(); if(root == null){ return res; } LinkedList
que = new LinkedList
(); que.add(root); int curCount = 1; int nextCount = 0; List
item = new ArrayList
(); while(!que.isEmpty()){ TreeNode tn = que.poll(); item.add(tn.val); curCount--; if(tn.left != null){ que.add(tn.left); nextCount++; } if(tn.right != null){ que.add(tn.right); nextCount++; } if(curCount == 0){ res.add(new ArrayList
(item)); item = new ArrayList
(); curCount = nextCount; nextCount = 0; } } return res; }}

 类似的有, , , , , .

转载于:https://www.cnblogs.com/Dylan-Java-NYC/p/4825021.html

你可能感兴趣的文章
远程桌面(3389)复制(拖动)文件
查看>>
转 lucene3搜索引擎,索引建立搜索排序分页高亮显示, IKAnalyzer分词
查看>>
bootstrap datetimepicker 位置错误
查看>>
9结构型模式之代理模式
查看>>
第二节 整型数据
查看>>
Python 序列
查看>>
Liferay的架构:缓存(第一部分)
查看>>
初识B/S结构编程技术
查看>>
方法、hadoop源码之JobQueueTaskScheduler-by小雨
查看>>
页面重构总结
查看>>
IO 函数
查看>>
Unity V3 初步使用 —— 为我的.NET项目从简单三层架构转到IOC做准备
查看>>
JSP页面间传递参数
查看>>
VSNETcodePrint 2005 & SQL ServerPrint 2005
查看>>
java数组基本操作
查看>>
String的indexOf()用于获取字符串中某个子字符串的位置
查看>>
shell 脚本运算符
查看>>
杭电 1711 Number Sequence
查看>>
又一道软通动力7K月薪面试题——银行业务调度系统
查看>>
Matlab画图-非常具体,非常全面
查看>>