题目
题解
叶子节点定义左孩子和右孩子都为 null 时叫叶子节点。
当根结点root节点左右孩子都为空时,返回 1。
当根结点root节点左右孩子有一个为空时,返回不为空的孩子节点的深度。
当根结点root节点左右孩子都不为空时,返回左右孩子较小深度的节点值。
递归:分别递归左子树,和右子树记下左子树和右子树的深度,如果左子树和右子树有一个是0结果是不为0的树的深度+1,都不为0取左子树和右子树最小的值+1。
bfs:广度优先,直接套广度优先的模板,拿个队列存TreeNode,广度一层一层下去,每一层深度depth+1,每一层判断左子树和右子树同时为null返回深度。
代码
//递归解法:
public int minDepth(TreeNode root) {
if (root == null) {
return 0;
}
int left = minDepth(root.left);
int right = minDepth(root.right);
if (left == 0 || right == 0) {
return left + right + 1;
}
return Math.min(left, right) + 1;
}
//bfs广度优先
public int minDepth1(TreeNode root) {
if (root == null) {
return 0;
}
//队列里面放树
Queue<TreeNode> q=new LinkedList<>();
q.offer(root);
int depth=1;
while(!q.isEmpty()){
int sz=q.size();
for(int i=0;i<sz;i++){
TreeNode cur=q.poll();
if(cur.left==null&&cur.right==null){
return depth;
}
if(cur.left!=null){
q.offer(cur.left);
}
if(cur.right!=null){
q.offer(cur.right);
}
}
depth++;
}
return depth;
}
备注
本文正在参与「掘金 2021 春招闯关活动」, 点击查看。