思路:
广度优先遍历
代码:
class Solution {
public int[] levelOrder(TreeNode root) {
if(root==null){
//创建空数组的格式为new int[0]
return new int[0];
}
Queue<TreeNode> queue=new LinkedList<>();
queue.add(root);
List<Integer> path=new ArrayList<>();
while(!queue.isEmpty()){
TreeNode node=queue.poll();
path.add(node.val);
if(node.left!=null){
queue.add(node.left);
}
if(node.right!=null){
queue.add(node.right);
}
}
int[] res=new int[path.size()];
for(int i=0;i<path.size();i++){
res[i]=path.get(i);
}
return res;
}
}
分解:
1)创建一个queue(LinkedList队列),和一个ArrayList(数组)
2)一定要判断当前节点的左右节点是否为null
3)最后将ArrayList转换为int[]没有线程的方法函数,要通过一个个遍历完成
4)空数组的创建是new int[0]
int[] res=new int[path.size()];
for(int i=0;i<path.size();i++){
res[i]=path.get(i);
}
复杂度分析:
时间复杂度:O(N) 每个值都最多被加入和弹出队列一次
空间复杂度:O(N) 额外使用了一个队列,最差情况下,即当树为平衡二叉树时,最多有 N/2 个树节点同时在 queue
中