给定一棵二叉树,找出它的最小深度。最小深度是沿着从根节点到最近叶节点的最短路径的节点数目。
思路一:递归。
- 当节点左右子树都为null时,返回0
- 当左子树为null,返回右子树递归+1;
- 当右字数为null,返回左子树递归+1;
- 当左右子树都不为空,返回左右子树递归最小值。
public class Solution {
public int run(TreeNode root) {
//当节点左右子树都为null时,返回0
if(root==null)
return 0;
//当左子树为null,返回右子树递归+1;
if(root.left==null)
return run(root.right)+1;
//当右字数为null,返回左子树递归+1;
if(root.right==null)
return run(root.left)+1;
//当左右子树都不为空,返回左右子树递归最小值。
int right=run(root.right)+1;
int left=run(root.left)+1;
return left>right?right:left;
}
}
思路二:非递归层次遍历
- 用一个队列存数据
- 遍历每层节点,可用循环,遍历完后深度加1.
- 当存在左右子树都为null时,返回depth
import java.util.*;
public class Solution {
public int run(TreeNode root) {
Queue<TreeNode> queue=new LinkedList<>();
if(root==null)
return 0;
queue.add(root);
int depth=1;
while(!queue.isEmpty()){
int len=queue.size();
//遍历每层
while(len>0){
TreeNode tree=queue.poll();
if(tree.left==null && tree.right==null)
return depth;
if(tree.left!=null)
queue.add(tree.left);
if(tree.right!=null)
queue.add(tree.right);
len--;
}
depth++;
}
return depth;
}
}