二叉树最小深度
程序员文章站
2022-07-14 18:06:15
...
1、递归版
public class Solution {
public int run(TreeNode root) {
if(root==null){
return 0;
}
if(root.left==null&&root.right==null){
return 1;
}
if(root.left==null || root.right==null){
return Math.max(run(root.left),run(root.right))+1;
}
return Math.min(run(root.left),run(root.right))+1;
}
}
2、非递归
import java.util.*;
public class Solution {
public int run(TreeNode root) {
if(root==null) return 0;
if(root.left==null && root.right==null)
return 1;
LinkedList<TreeNode> queue=new LinkedList<>();
queue.add(root);
int count=0;
while(!queue.isEmpty()){
int len=queue.size();
count++;
for(int i=0; i<len; i++){
TreeNode temp=queue.remove(0);
if(temp.left==null&&temp.right==null)
return count;
if(temp.left!=null)
queue.add(temp.left);
if(temp.right!=null)
queue.add(temp.right);
}
}
return count;
}
}
上一篇: 【Leetcode】Two Sum题解
下一篇: 构造方法中使用this的含义