从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
提示:
- 节点总数 <= 1000
题解:
算法流程:
/**
* 剑指 Offer 32 - I. 从上到下打印二叉树
*/
public int[] levelOrder(TreeNode root) {
if (root == null) {
return new int[0];
}
// 树的层次遍历即广度优先遍历 BFS,优先想到队列
List<Integer> res = new ArrayList<>();
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
res.add(node.val);
// 将当前结点的左、右孩子加入到队尾
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
int[] result = new int[res.size()];
for (int i = 0; i < result.length; i++) {
result[i] = res.get(i);
}
return result;
}
来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof