102. Binary Tree Level Order Traversal(BFS)
1、迭代的方法
用树的高度控制插入位置
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res=new LinkedList<List<Integer>>();
level(res,root,0);
return res;
}
public void level(List<List<Integer>> res,TreeNode root,int height) {
if(root==null)
return;
if(height>=res.size())
res.add(new LinkedList());
res.get(height).add(root.val);
level(res,root.left,height+1);
level(res,root.right,height+1);
}
}
2、采用队列的方式(Queue)
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
Queue<TreeNode> nodeQueue = new LinkedList<>();
List<List<Integer>> res=new ArrayList<List<Integer>>();
if(root==null)
return res;
nodeQueue.offer(root);
while(!nodeQueue.isEmpty()){
List<Integer> al=new ArrayList<Integer>();
int len=nodeQueue.size();
for(int i=0;i<len;i++){
if(nodeQueue.peek().left!=null)nodeQueue.add(nodeQueue.peek().left);
if(nodeQueue.peek().right!=null)nodeQueue.add(nodeQueue.peek().right);
al.add(nodeQueue.poll().val);
}
res.add(al);
}
return res;
}
}