广度优先搜索:
每次将一个节点周围的所有节点加入队列。适合找最短距离,但空间复杂度高,而且没有深度优先搜索的递归代码好写。 ?
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null){
return new ArrayList<>();
}
List<List<Integer>> result=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
while(queue.size()!=0){
int size=queue.size();
List<Integer> temp=new ArrayList<>();
for(int i=0;i<size;++i){
TreeNode currentNode=queue.poll();
temp.add(currentNode.val);
if(currentNode.left!=null){
queue.offer(currentNode.left);
}
if(currentNode.right!=null){
queue.offer(currentNode.right);
}
}
result.add(temp);
}
return result;
}
}
?
class Solution {
public List<List<Integer>> levelOrderBottom(TreeNode root) {
if(root==null){
return new ArrayList<>();
}
List<List<Integer>> result=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
while(queue.size()!=0){
int size=queue.size();
List<Integer> temp=new ArrayList<>();
for(int i=0;i<size;++i){
TreeNode currentNode=queue.poll();
temp.add(currentNode.val);
if(currentNode.left!=null){
queue.offer(currentNode.left);
}
if(currentNode.right!=null){
queue.offer(currentNode.right);
}
}
result.add(0,temp);
}
return result;
}
}
?
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
if(root==null){
return new ArrayList<>();
}
List<List<Integer>> result=new ArrayList<>();
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
int depth=1;
while(queue.size()!=0){
int size=queue.size();
List<Integer> temp=new ArrayList<>();
for(int i=0;i<size;++i){
TreeNode currentNode=queue.poll();
temp.add(currentNode.val);
if(currentNode.left!=null){
queue.offer(currentNode.left);
}
if(currentNode.right!=null){
queue.offer(currentNode.right);
}
}
if(depth%2==0){
Collections.reverse(temp);
}
result.add(temp);
++depth;
}
return result;
}
}
?
class Solution {
public int minDepth(TreeNode root) {
if(root==null){
return 0;
}
Queue<TreeNode> queue=new LinkedList<>();
queue.offer(root);
int depth=1;
while(queue.size()!=0){
int size=queue.size();
for(int i=0;i<size;++i){
TreeNode currentNode=queue.poll();
if(currentNode.left==null&¤tNode.right==null){
return depth;
}
if(currentNode.left!=null){
queue.offer(currentNode.left);
}
if(currentNode.right!=null){
queue.offer(currentNode.right);
}
}
++depth;
}
return depth;
}
}
?
|