难度中等1388收藏分享切换为英文接收动态反馈
给你二叉树的根节点 root
,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7] 输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1] 输出:[[1]]
示例 3:
输入:root = [] 输出:[]
提示:
- 树中节点数目在范围
[0, 2000]
内 -1000 <= Node.val <= 1000
通过次数619,470提交次数954,187
package com.study.treestudy;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
public class TreeToArray {
public static void main(String[] args) {
// TODO Auto-generated method stub
/*
* 3
* / \
* 9 20
* / \
* 15 7
* */
TreeNode root = new TreeNode(3);
TreeNode left = new TreeNode(9);
TreeNode right = new TreeNode(20);
TreeNode rightleft = new TreeNode(15);
TreeNode rightright = new TreeNode(7);
root.left = left;
root.right = right;
right.left = rightleft;
right.right = rightright;
System.out.println(levelOrder2(root).toString());
prevOrder(root);
System.out.println();
middleOrder(root);
System.out.println();
lastOrder(root);
System.out.println();
levelOrderout(root);
}
static List<List<Integer>> levels = new ArrayList<List<Integer>>();
// 递归层序遍历(二维数组方法)
public static void helper(TreeNode node, int level) {
if (levels.size() == level) {
levels.add(new ArrayList<Integer>());
}
levels.get(level).add(node.val);
if (node.left != null) {
helper(node.left, level + 1);
}
if (node.right != null) {
helper(node.right, level + 1);
}
}
public static List<List<Integer>> levelOrder(TreeNode root) {
if (root == null) {
return levels;
}
helper(root, 0);
return levels;
}
// 队列层序遍历(二维数组方法)
public static List<List<Integer>> levelOrder2(TreeNode root) {
List<List<Integer>> levels = new ArrayList<List<Integer>>();
if (root == null) {
return levels;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> level = new ArrayList<Integer>();
int currentLevel = queue.size();
for (int i = 1; i <= currentLevel; i++) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
levels.add(level);
}
return levels;
}
// 先序遍历直接输出的
public static void prevOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + " ");
prevOrder(root.left);
prevOrder(root.right);
}
// 中序遍历直接输出的
public static void middleOrder(TreeNode root) {
if (root == null) {
return;
}
middleOrder(root.left);
System.out.print(root.val + " ");
middleOrder(root.right);
}
// 后续遍历直接输出的
public static void lastOrder(TreeNode root) {
if (root == null) {
return;
}
lastOrder(root.left);
lastOrder(root.right);
System.out.print(root.val + " ");
}
// 层序遍历直接输出的
public static void levelOrderout(TreeNode root) {
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
int size = queue.size();
for (int i = 1; i <= size; i++) {
TreeNode cur = queue.poll();
System.out.print(cur.val + " ");
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
}
}
}