坚持刷题,老年痴呆追不上我,今天刷:二叉树的层序遍历
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Queue;
class TreeNode {
int val;
TreeNode left;
TreeNode right;
public TreeNode(int val) {
this.val = val;
}
}
public class BinaryTreeLevelOrderTraversal {
public static List<List<Integer>> levelOrderTraversal(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 levelSize = queue.size();
List<Integer> levelNodes = new ArrayList<>();
for (int i = 0; i < levelSize; i++) {
TreeNode node = queue.poll();
levelNodes.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
result.add(levelNodes);
}
return result;
}
public static void main(String[] args) {
// 构建一个二叉树用于测试
TreeNode root = new TreeNode(3);
root.left = new TreeNode(9);
root.right = new TreeNode(20);
root.right.left = new TreeNode(15);
root.right.right = new TreeNode(7);
List<List<Integer>> traversalResult = levelOrderTraversal(root);
System.out.println("层序遍历结果:");
System.out.println(traversalResult);
}
}
levelOrderTraversal
方法返回一个List<List<Integer>>
,其中每个内部的List
表示一层的节点值levelNodes
中levelNodes
加入到结果集合result中这些扩展问题会在后续的刷题中逐一解决