二叉树最小深度

16 篇文章 1 订阅
13 篇文章 0 订阅

来源:https://www.nowcoder.com/practice/e08819cfdeb34985a8de9c4e6562e724?tpId=46&tqId=29030&tPage=1&rp=1&ru=/ta/leetcode&qru=/ta/leetcode/question-ranking

题目描述
minimum-depth-of-binary-tree
Given a binary tree, find its minimum depth.The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

问题分析:这个题有两种办法:第一种就是直接递归调用,这个办法好处就是理解起来方便,但是却需要把所有的节点都遍历一下,然后求出来最短的那个,需要的时间为T(n)。第二种就是采用层次遍历,这样哪怕树的结构是满二叉树,遍历到第一个节点的时候也可以结束,假如树高度为h,那我们遍历到2^(h-1) 的时候就可以结束遍历了,后面还有2^(h-1)-1个节点不用遍历。如果不是满二叉树,那需要遍历的就更少了,平均下来递归调用需要遍历T(n)次,层次遍历需要T(n/4)次,这里n代表节点总数。

代码如下:

递归算法:
 

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; 
} 
}

非递归的层次遍历算法:(推荐)

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;
        }
        Queue queue = new LinkedList();
        queue.add(root);
        int level = 1;
        while(!queue.isEmpty()){
            int size = queue.size();
            for(int i=0;i<size;i++){
                TreeNode node = queue.poll();
                if(node.left==null&&node.right==null){
                    return level;
                }
                if(node.left!=null){
                    queue.add(node.left);
                }
                if(node.right!=null){
                    queue.add(node.right);
                }
            }
            level++;
        }
        return level;
    }
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值