leetcode — binary-tree-level-order-traversal
import org.lep.leetcode.binarytreeinordertraversal.BinaryTreeInOrderTraversal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Stack;
/**
* Source : https://oj.leetcode.com/problems/binary-tree-level-order-traversal/
*
*
* 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]
* ]
*
*/
public class BinaryTreeLevelOrderTraversal {
/**
* 按层次输出二叉树的遍历结果
*
* 使用BFS,借助栈实现,因为需要知道节点属于第几层,在入栈的时候就需要把节点和节点所在层level入栈
*
* @param root
* @return
*/
public List<List<Integer>> levelOrderTraversal (TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return null;
}
Stack<LevelNode> stack = new Stack<LevelNode>();
int currentLevel = 0;
int lastLevel = 0;
stack.push(new LevelNode(root, currentLevel));
List<Integer> levelList = new ArrayList<Integer>();
result.add(levelList);
while (stack.size() > 0) {
currentLevel = lastLevel;
LevelNode node = stack.firstElement();
stack.remove(0);
if (node.node == null) {
continue;
}
if (node.level != currentLevel) {
levelList = new ArrayList<Integer>();
result.add(levelList);
lastLevel++;
}
result.get(lastLevel).add(node.node.value);
stack.push(new LevelNode(node.node.leftChild, currentLevel + 1));
stack.push(new LevelNode(node.node.rightChild, currentLevel + 1));
}
return result;
}
/**
*
* 按层次输出树
*
* 使用两个list分别保存当前层的node和下一层的node
* 先将节点加入当前层
* 遍历当前层,将每个节点的左右子节点加入下一层的list
* 遍历完成之后,swap当前层和下一层的list,再次遍历
*
* @param root
* @return
*/
public List<List<Integer>> levelOrderTraversal1 (TreeNode root) {
List<List<Integer>> result = new ArrayList<List<Integer>>();
if (root == null) {
return result;
}
List<TreeNode> curList = new ArrayList<TreeNode>();
List<TreeNode> nextList = new ArrayList<TreeNode>();
curList.add(root);
while (curList.size() > 0) {
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < curList.size(); i++) {
if (curList.get(i) == null) {
continue;
}
list.add(curList.get(i).value);
nextList.add(curList.get(i).leftChild);
nextList.add(curList.get(i).rightChild);
}
if (list.size() > 0) {
result.add(list);
}
curList.clear();
curList.addAll(nextList);
nextList.clear();
}
return result;
}
public static void print (List<List<Integer>> lists) {
StringBuffer buffer = new StringBuffer();
buffer.append("[\n");
for (int i = 0; i < lists.size(); i++) {
buffer.append(Arrays.toString(lists.get(i).toArray(new Integer[lists.get(i).size()])));
buffer.append(",\n");
}
if (lists.size() > 0) {
buffer.deleteCharAt(buffer.length()-2);
}
buffer.append("]");
System.out.println(buffer.toString());
}
public TreeNode createTree (char[] treeArr) {
TreeNode[] tree = new TreeNode[treeArr.length];
for (int i = 0; i < treeArr.length; i++) {
if (treeArr[i] == '#') {
tree[i] = null;
continue;
}
tree[i] = new TreeNode(treeArr[i]-'0');
}
int pos = 0;
for (int i = 0; i < treeArr.length && pos < treeArr.length-1; i++) {
if (tree[i] != null) {
tree[i].leftChild = tree[++pos];
if (pos < treeArr.length-1) {
tree[i].rightChild = tree[++pos];
}
}
}
return tree[0];
}
private class LevelNode {
TreeNode node;
int level;
public LevelNode(TreeNode node, int level) {
this.node = node;
this.level = level;
}
}
private class TreeNode {
TreeNode leftChild;
TreeNode rightChild;
int value;
public TreeNode(int value) {
this.value = value;
}
public TreeNode() {
}
}
public static void main(String[] args) {
BinaryTreeLevelOrderTraversal binaryTreeLevelOrderTraversal = new BinaryTreeLevelOrderTraversal();
char[] arr = new char[]{'3','9','2','#','#','1','7'};
TreeNode tree = binaryTreeLevelOrderTraversal.createTree(arr);
print(binaryTreeLevelOrderTraversal.levelOrderTraversal(tree));
print(binaryTreeLevelOrderTraversal.levelOrderTraversal1(tree));
}
}
leetcode — binary-tree-level-order-traversal的更多相关文章
- LeetCode:Binary Tree Level Order Traversal I II
LeetCode:Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of ...
- [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 II @ Python
原题地址:http://oj.leetcode.com/problems/binary-tree-level-order-traversal-ii/ 题意: Given a binary tree, ...
- LeetCode: Binary Tree Level Order Traversal 解题报告
Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of its nodes ...
- [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 与 Binary Tree Zigzag Level Order Traversal,两种按层次遍历树的方式,分别两个队列,两个栈实现
Binary Tree Level Order Traversal Given a binary tree, return the level order traversal of its nodes ...
- 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 II
题目: Given a binary tree, return the bottom-up level order traversal of its nodes' values. (ie, from ...
随机推荐
- js 原生转json 可以v8中运行
// load("D:/jsontest.js"); function test1(vvv) { print(vvv); } //把json str 转 json obj func ...
- javascript 变量的引入、变量的声明、变量的初始化
变量的引入及声明和初始化: 变量: 操作的数据都是在内存中操作 Js中存储数据使用变量的方式(名称,值--->数据) Js中声明变量都用var--->存储数据,数据应该有对应的数据类型 存 ...
- 如何给网站添加IE浏览器升级提示
1.在代码编辑器中(如Notepad++)打开网站头部模板 2.使用<!––[if IE]>语句添加升级提示,如: 判断是否IE(包含使用IE内核的浏览器) <!––[if IE]& ...
- vue中实现图片全屏缩放预览,支持移动端
# 安装 npm install vue-photo-preview --save # 引入 import preview from 'vue-photo-preview' import 'vue-p ...
- 201771010118 马昕璐 《面向对象设计 java》第十七周实验总结
1.实验目的与要求 (1) 掌握线程同步的概念及实现技术: (2) 线程综合编程练习 2.实验内容和步骤 实验1:测试程序并进行代码注释. 测试程序1: l 在Elipse环境下调试教材651页程序1 ...
- 【react】---17新增的生命周期
一.废除的生命周期 官网文档指出使用这些生命周期的代码会在未来版本的react中更容易产生bug,尤其是对于异步渲染的版本 由于未来采用异步渲染机制,所以即将在17版本中去掉的生命周期钩子函数 com ...
- framework7 入门(数据绑定)
数据绑定是用template7,官网,framework7内置template7,不用单独下载,下面介绍一些简单的绑定 当你的数据是个数组 return{ data:function(){ let i ...
- Android找回密码功能 手机找回、邮箱找回
找回密码功能设计:https://blog.csdn.net/qq_33472765/article/details/82287404?utm_source=blogxgwz0 手机找回:https: ...
- 算法与数据结构(十二) 散列(哈希)表的创建与查找(Swift版)
散列表又称为哈希表(Hash Table), 是为了方便查找而生的数据结构.关于散列的表的解释,我想引用维基百科上的解释,如下所示: 散列表(Hash table,也叫哈希表),是根据键(Key)而直 ...
- 在vue中使用svg sprite
概述 这几天研究了一下在vue中使用svg sprite,有些心得,记录下来,供以后开发时参考,相信对其它人也有用. 在vue中导入svg 在vue中导入svg的方法有很多种,比如在img标签的src ...