[LintCode] Binary Tree Level Order Traversal(二叉树的层次遍历)
描述
给出一棵二叉树,返回其节点值的层次遍历(逐层从左往右访问)
样例
给一棵二叉树 {3,9,20,#,#,15,7} :
3
/ \
9 20
/ \
15 7
返回他的分层遍历结果:
[
[3],
[9,20],
[15,7]
]
挑战
挑战1:只使用一个队列去实现它
挑战2:用BFS算法来做
package com.ossez.lang.tutorial.tests.lintcode; import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue; import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import com.ossez.lang.tutorial.models.TreeNode; /**
* <p>
* 69
* <ul>
* <li>@see <a href=
* "https://www.cwiki.us/display/ITCLASSIFICATION/Binary+Tree+Level+Order+Traversal">https://www.cwiki.us/display/ITCLASSIFICATION/Binary+Tree+Level+Order+Traversal</a>
* <li>@see<a href=
* "https://www.lintcode.com/problem/binary-tree-level-order-traversal">https://www.lintcode.com/problem/binary-tree-level-order-traversal</a>
* </ul>
* </p>
*
* @author YuCheng
*
*/
public class LintCode0069LevelOrderTest { private final static Logger logger = LoggerFactory.getLogger(LintCode0069LevelOrderTest.class); /**
*
*/
@Test
public void testMain() {
logger.debug("BEGIN");
String data = "{3,9,20,#,#,15,7}"; TreeNode tn = deserialize(data);
System.out.println(levelOrder(tn)); } /**
* Deserialize from array to tree
*
* @param data
* @return
*/
private TreeNode deserialize(String data) {
// NULL CHECK
if (data.equals("{}")) {
return null;
} ArrayList<TreeNode> treeList = new ArrayList<TreeNode>(); data = data.replace("{", "");
data = data.replace("}", "");
String[] vals = data.split(","); // INSERT ROOT
TreeNode root = new TreeNode(Integer.parseInt(vals[0]));
treeList.add(root); int index = 0;
boolean isLeftChild = true;
for (int i = 1; i < vals.length; i++) {
if (!vals[i].equals("#")) {
TreeNode node = new TreeNode(Integer.parseInt(vals[i]));
if (isLeftChild) {
treeList.get(index).left = node;
} else {
treeList.get(index).right = node;
}
treeList.add(node);
} // LEVEL
if (!isLeftChild) {
index++;
} // MOVE TO RIGHT OR NEXT LEVEL
isLeftChild = !isLeftChild;
} return root; } private List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<TreeNode>();
List<List<Integer>> rs = new ArrayList<List<Integer>>(); // NULL CHECK
if (root == null) {
return rs;
} queue.offer(root); while (!queue.isEmpty()) {
int length = queue.size();
List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < length; i++) {
TreeNode curTN = queue.poll();
list.add(curTN.val);
if (curTN.left != null) {
queue.offer(curTN.left);
}
if (curTN.right != null) {
queue.offer(curTN.right);
}
} rs.add(list);
} return rs;
}
}
点评
这个程序可以使用队列的广度优先算法来进行遍历。
需要注意的是,因为在输出结果的时候需要按照层级来进行输出,那么需要考虑的一个算法就是二叉树的层级遍历算法。
这个算法要求在遍历的时候记录树的层级。
[LintCode] Binary Tree Level Order Traversal(二叉树的层次遍历)的更多相关文章
- LeetCode 102. Binary Tree Level Order Traversal 二叉树的层次遍历 C++
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...
- 【LeetCode】Binary Tree Level Order Traversal(二叉树的层次遍历)
这道题是LeetCode里的第102道题. 题目要求: 给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15 ...
- 102 Binary Tree Level Order Traversal 二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值. (即zhu'ceng'de,从左到右访问).例如:给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 ...
- leetcode 102.Binary Tree Level Order Traversal 二叉树的层次遍历
基础为用队列实现二叉树的层序遍历,本题变体是分别存储某一层的元素,那么只要知道,每一层的元素都是上一层的子元素,那么只要在while循环里面加个for循环,将当前队列的值(即本层元素)全部访问后再执行 ...
- Leetcode102. Binary Tree Level Order Traversal二叉树的层次遍历
给定一个二叉树,返回其按层次遍历的节点值. (即逐层地,从左到右访问所有节点). 例如: 给定二叉树: [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 返回其 ...
- leetcode 题解:Binary Tree Level Order Traversal (二叉树的层序遍历)
题目: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to ri ...
- 【LeetCode】102. Binary Tree Level Order Traversal 二叉树的层序遍历 (Python&C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客:http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 BFS DFS 日期 题目地址:https://lee ...
- LeetCode 102. Binary Tree Level Order Traversal02. 二叉树的层次遍历 (C++)
题目: Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to ri ...
- [LeetCode] Binary Tree Level Order Traversal 二叉树层序遍历
Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, ...
随机推荐
- Oracle错误——ORA-12704:字符集不匹配
错误 在查询使用coalesce把字符串进行转换时,报错ORA-12704:字符集不匹配 如下图 解决方法 在网上找了很多方法,有使用Translate转换的:有使用to_char()的,经过测试不符 ...
- noip模拟【ping】
70:很容易想到的是枚举每一个可能的答案来判断是否可行,取最优即可,贪心选择. 100:满足题目条件的这个距离是满足单调性的.如果x不行,那么大于x的距离都不行,二分答案. 学会运用二分,by ws_ ...
- Linux/shell: Concatenate multiple lines to one line
$ cat file START Unix Linux START Solaris Aix SCO 1. Join the lines following the pattern START with ...
- 论文笔记之:Heterogeneous Face Attribute Estimation: A Deep Multi-Task Learning Approach
Heterogeneous Face Attribute Estimation: A Deep Multi-Task Learning Approach 2017.11.28 Introductio ...
- 论文笔记之:Action-Decision Networks for Visual Tracking with Deep Reinforcement Learning
论文笔记之:Action-Decision Networks for Visual Tracking with Deep Reinforcement Learning 2017-06-06 21: ...
- [js] - js中类(伪)数组装正规数组
今天的js中使用了自定义的原型方法去重后,再调用这个获取的去重的数组传入另一个含有for循环的方法时, console.log出错: dimensions:createTime,华联石化,海油石化,青 ...
- 防止网站检测出Selenium的window.navigator.webdriver属性
只需在Chromeoptions对象中添加一个属性即可解决 import time from selenium.webdriver import Chrome, ChromeOptions optio ...
- Hexo搭建(VPS)
都说 hexo 是静态的 Blog,当时不明觉厉= =.后来终于知道了什么意思......所谓的静态,其实就是因为你不能改云端,而是依赖本地数据,然后使用命令将本地数据变成 web 数据再使用浏览器进 ...
- SourceTree/git解决pre-commit hook failed的问题
一. git commit -m 'xxx' 出现问题 今天在上传项目的时候在commit阶段遇到一个问题,无论是在Sourcetree上传还是用命令git commit -m 'xxx'都报了一下错 ...
- win10常用命令和设置总结
1.常用命令 exit:退出cmd面板; cls:清除cmd面板; 2.常用设置 2.1 services.msc 禁用:以后怎样都不会运行;手动:是打开某些用到它的程序要用到该服务时才会运行; 自动 ...