从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
解法一:BFS
时间复杂度 O(N) : N 为二叉树的节点数量,即 BFS 需循环 N 次。
空间复杂度 O(N): 最差情况下,即当树为平衡二叉树时,最多有N/2 个树节点同时在 queue 中,使用 O(N) 大小的额外空间。
class Solution {
public int[] levelOrder(TreeNode root) {
if(root == null) return new int[0];
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
ArrayList<Integer> ans = new ArrayList<>();
while(!queue.isEmpty()) {
TreeNode node = queue.poll();
ans.add(node.val);
if(node.left != null) queue.add(node.left);
if(node.right != null) queue.add(node.right);
}
int[] res = new int[ans.size()];
for(int i = 0; i < ans.size(); i++)
res[i] = ans.get(i);
return res;
}
}

该博客介绍了如何使用广度优先搜索(BFS)策略,从上到下、从左到右层次遍历并打印二叉树的所有节点。提供了一个Java实现的解决方案,其时间复杂度为O(N),空间复杂度为O(N)。

265

被折叠的 条评论
为什么被折叠?



