Binary Tree Level Order Traversal 解答
Question
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,#,#,15,7}
,
3
/ \
9 20
/ \
15 7
return its level order traversal as:
[
[3],
[9,20],
[15,7]
]
Solution -- Two Queues
Classic solution for BFS problem is to use two queues. One for current level, and the other for next level. This method is to visit tree level by level. Time complexity is O(n), space cost is O(n), n is the number of nodes in tree.
/**
* 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>> levelOrder(TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null)
return result;
Deque<TreeNode> current = new ArrayDeque<TreeNode>();
Deque<TreeNode> next;
TreeNode tmpNode;
current.addLast(root);
while (current.size() > 0) {
// Refresh next queue
next = new ArrayDeque<TreeNode>();
List<Integer> tmpList = new ArrayList<Integer>();
while (current.size() > 0) {
tmpNode = current.pop();
if (tmpNode.left != null)
next.addLast(tmpNode.left);
if (tmpNode.right != null)
next.addLast(tmpNode.right);
tmpList.add(tmpNode.val);
}
// Refresh prev queue
current = next;
result.add(tmpList);
}
return result;
}
}
Simplied version
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque class Solution:
def levelOrder(self, root: TreeNode) -> List[List[int]]:
result = []
if not root:
return result
queue = deque()
queue.append(root)
while queue:
level = []
size = len(queue)
for i in range(size):
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(level)
return result
Binary Tree Level Order Traversal 解答的更多相关文章
- Binary Tree Level Order Traversal II 解答
Question Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, ...
- LeetCode之Binary Tree Level Order Traversal 层序遍历二叉树
Binary Tree Level Order Traversal 题目描述: Given a binary tree, return the level order traversal of its ...
- [LeetCode] Binary Tree Level Order Traversal II 二叉树层序遍历之二
Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from left ...
- [LeetCode] Binary Tree Level Order Traversal 二叉树层序遍历
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...
- 【leetcode】Binary Tree Level Order Traversal I & II
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...
- 35. Binary Tree Level Order Traversal && Binary Tree Level Order Traversal II
Binary Tree Level Order Traversal OJ: https://oj.leetcode.com/problems/binary-tree-level-order-trave ...
- LeetCode:Binary Tree Level Order Traversal I II
LeetCode:Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of ...
- 【Binary Tree Level Order Traversal II 】cpp
题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from ...
- lettcode-102:Binary Tree Level Order Traversal (Java)
Binary Tree Level Order Traversal 二叉树的层序遍历 两种方式: 1.用两个queue交替表示每一层的节点 2.用两个node,一个表示当前层的最后一个节点,一个表示下 ...
随机推荐
- 记忆2--记忆的"记"和"忆"
有时候也会想,我们是如何记住东西的?是如何想起来的?在写这篇文章的时候,想起初中的时候(应当是初二),语文老师检查唐诗背诵,在下面觉得已经能背起来的时候,去向老师背诵的时候,忘记了开头,干急想不起来, ...
- Tomcat部署项目通过—IP地址:端口访问
如题所示,实现效果图如下: 设置如下: (1)修改${tomcat}/config/sever.xml文件虚拟内容目录: <Engine name="Catalina" de ...
- 高精度快速幂(Java版)
import java.io.*; import java.math.*; import java.util.*; import java.text.*; public class Main { pu ...
- Handler消息机制实现更新主UI
如下实现的是简单的更新主UI的方法,用Handler消息机制 将textview的内容每隔一秒实现num++ /* * handler消息机制 * asynctask异步任务 * * httpcli ...
- Ajax_post发送
$('#img_file_del_3').click(function() { var data={name:$('#img_file_del_3').attr('name')}; var url=' ...
- eclipse配置maven + 创建maven项目
登录|注册 努力+坚持,而且还很年轻 目录(?)[+] 在现实的企业中,以低成本.高效率.高质量的完成项目,不仅仅需要技术大牛,企业更加需要管理大牛,管理者只懂技术是远远不够的.当 ...
- EasyUI 两个日期比较
两个日期进行比较,后一个日期不能早于晚一个日期.需要自己去扩展validatebox的方法 1.对比2个密码是否相同 $.extend($.fn.validatebox.defaults.rules, ...
- 关于MemoryBarrier
备注:OSG OpenThread::Atomic.cpp中MemoryBarrier(); Atomic::operator unsigned() const { #if defined(_OPE ...
- ORA-00119: invalid specification for system parameter LOCAL_LISTENER
重启oracle是提示错误ORA-00119: invalid specification for system parameter LOCAL_LISTENER. 解决方法: 命令查看错误信息:oe ...
- char值码对应大全
Char("0") 为0的字符Char("1") Char("2") Char("3") Char("4&qu ...