求二叉树的层序遍历
Posted 编程实战与原理
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了求二叉树的层序遍历相关的知识,希望对你有一定的参考价值。
给定一个二叉树,返回该二叉树层序遍历的结果,(从左到右,一层一层地遍历)
例如:
给定的二叉树是{3,9,20,#,#,15,7},
输出
[
[3],
[9,20],
[15,7]
]
输入:
{1,2,3,4,#,#,5}
复制
返回值:
[[1],[2,3],[4,5]]
代码实现如下:
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
public class Test {
public static void main(String[] args) {
TreeNode t1 = new TreeNode(1);
t1.left = new TreeNode(2);
t1.right = new TreeNode(3);
t1.right.left = new TreeNode(4);
t1.right.right = new TreeNode(5);
System.out.println(levelNum(t1));
}
public static ArrayList<ArrayList<Integer>> levelNum(TreeNode node) {
ArrayList<ArrayList<Integer>> arrayLists = new ArrayList<>();
if (null == node) {
return arrayLists;
}
//用于存储每一层的节点
Queue<TreeNode> queue = new LinkedList<>();
queue.add(node);
while (!queue.isEmpty()) {
//用于存储当前遍历这一层的节点
ArrayList<Integer> arrayList = new ArrayList<>();
int n = queue.size();
for (int i = 0; i < n; i++) {
TreeNode tn = queue.poll();
arrayList.add(tn.val);
if (null != tn.left) {
queue.add(tn.left);
}
if (null != tn.right) {
queue.add(tn.right);
}
}
arrayLists.add(arrayList);
}
return arrayLists;
}
/**
* 定义树
*/
public static class TreeNode {
private int val;
private TreeNode left;
private TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public int getVal() {
return val;
}
public void setVal(int val) {
this.val = val;
}
public TreeNode getLeft() {
return left;
}
public void setLeft(TreeNode left) {
this.left = left;
}
public TreeNode getRight() {
return right;
}
public void setRight(TreeNode right) {
this.right = right;
}
}
}
以上是关于求二叉树的层序遍历的主要内容,如果未能解决你的问题,请参考以下文章
#yyds干货盘点# 面试必刷TOP101:求二叉树的层序遍历