
剑指 Offer 32 - I. 从上到下打印二叉树
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。
例如:
给定二叉树: [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回:
[3,9,20,15,7]
提示:
节点总数 <= 1000
解法一:BFS 遍历
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public int[] levelOrder(TreeNode root) {
if (root == null) return new int[0];//空数组返回
Queue<TreeNode> qu = new LinkedList<>();//需要借助一个队列 实现bfs的二叉树遍历
ArrayList<Integer> list = new ArrayList<>();//申请一个动态数组 添加节点
qu.offer(root);
while (qu.size()>0){
TreeNode temp = qu.poll();
list.add(temp.val);
if (temp.left != null) qu.offer(temp.left);
if (temp.right != null) qu.offer(temp.right);
}
//将ArrayList 转换 成 int[]
int[] res = new int[list.size()];
for (int i = 0; i < res.length; i++) {
res[i] = list.get(i);
}
return res;
}
}
- 创建者:师晓峰
- 创建时间:2022/6/6 18:14
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)