/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
1、返回结果无需返回Null值
给你二叉树的根节点 root ,返回其节点值的 层序遍历 。 (即逐层地,从左到右访问所有节点)。
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[15,7]]
示例 2:
输入:root = [1]
输出:[[1]]
示例 3:
输入:root = []
输出:[]
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//定义返回结果
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
//使用队列进行处理
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
//利用队列先进先出的性质,每次循环时,会把本层节点弹出并把下一层的节点依次放入队列中并
while (!queue.isEmpty()) {
int leaveSize = queue.size();
List<Integer> currLeve = new ArrayList<>();
for (int i = 0; i < leaveSize; i++) {
TreeNode currentNode = queue.poll();
assert currentNode != null;
currLeve.add(currentNode.val);
if (currentNode.left != null) {
queue.offer(currentNode.left);
}
if (currentNode.right != null) {
queue.offer(currentNode.right);
}
}
result.add(currLeve);
}
return result;
}
}
2、返回结果中遇到Null节点也返回
示例 1:
输入:root = [3,9,20,null,null,15,7]
输出:[[3],[9,20],[null,null,15,7]]
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
//定义返回结果
List<List<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
//使用队列进行处理
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
//利用队列先进先出的性质,每次循环时,会把本层节点弹出并把下一层的节点依次放入队列中并
while (!queue.isEmpty()) {
int leaveSize = queue.size();
List<Integer> currLeve = new ArrayList<>();
//判断下一层是否有不为空的节点->有不为空的才进行入队
boolean add = false;
Queue<TreeNode> temp = new LinkedList<>();
for (int i = 0; i < leaveSize; i++) {
TreeNode currentNode = queue.poll();
currLeve.add(currentNode == null ? null : currentNode.val);
temp.offer(currentNode == null ? null : currentNode.left);
temp.offer(currentNode == null ? null : currentNode.right);
if (currentNode != null && (currentNode.left != null || currentNode.right != null)) {
add = true;
}
}
if (add) {
queue.addAll(temp);
}
result.add(currLeve);
}
return result;
}
}
标签:遍历,currentNode,val,层序,queue,二叉树,TreeNode,null,root
From: https://www.cnblogs.com/czarQ/p/17662886.html