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

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

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:[  [3],  [9,20],  [15,7]]

难度:medium

题目:给定二叉树,返回其层次遍历结点值。

思路:队列(FIFO)

Runtime: 1 ms, faster than 86.63% of Java online submissions for Binary Tree Level Order Traversal.

Memory Usage: 37.5 MB, less than 100.00% of Java online submissions for Binary Tree Level Order Traversal.

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */class Solution {    public List
> levelOrder(TreeNode root) { List
> result = new ArrayList<>(); if (null == root) { return result; } Queue
queue = new LinkedList<>(); queue.add(root); int currentLevelCount = 1, nextLevelCount = 0; List
currentLevelElements = new ArrayList<>(); while (!queue.isEmpty()) { TreeNode node = queue.poll(); currentLevelElements.add(node.val); if (node.left != null) { queue.add(node.left); nextLevelCount++; } if (node.right != null) { queue.add(node.right); nextLevelCount++; } currentLevelCount--; if (0 == currentLevelCount) { result.add(currentLevelElements); currentLevelElements = new ArrayList<>(); currentLevelCount = nextLevelCount; nextLevelCount = 0; } } return result; }}

转载地址:http://wtkdm.baihongyu.com/

你可能感兴趣的文章
Qtum量子链作客第四届拉美商业科技大会
查看>>
volatile变量与普通变量的区别
查看>>
[MetalKit]34-Working-with-memory-in-Metal内存管理
查看>>
@ngrx入坑angular的schema,爽的一逼!
查看>>
教你用JS手写简单的秒表(精确到10ms,没有延迟)
查看>>
vue.js响应式原理解析与实现
查看>>
Block
查看>>
Android 导航栏如何轻松搞定
查看>>
LeetCode 406 Queue Reconstruction by Height
查看>>
dyld: Library not loaded: @rpath/Alamofire.framework/Alamofire
查看>>
Android-MeasureSpec那些事
查看>>
聊聊flink的logback配置
查看>>
开发了个 Flipper 调试工具的 Flutter 版本 SDK,让 Flutter 应用调试起来更容易
查看>>
spring cloud config将配置存储在数据库中
查看>>
HTTP代理ip的这些误区你知道吗?
查看>>
初探 Vue 生命周期和钩子函数
查看>>
探究防抖(debounce)和节流(throttle)
查看>>
为何把日志打印到控制台很慢?
查看>>
Java多线程-Callable和Future
查看>>
记一次用iview实现表格"合并"单元格的具体操作
查看>>