zoukankan      html  css  js  c++  java
  • [数据结构与算法]求给定二叉树的最小深度。最小深度是指树的根结点到最近叶子结点的最短路径上结点的数量。

    解题思路:

    刚开始想到的就是利用回溯,树的最小深度等于树的左右子树的最小深度+1;

    根据这个想法,写出解题算法

    public class Solution {
        public int run(TreeNode root) {
            TreeNode node = root;
            
    //递归的边界条件 如果当前节点为null 高度为0
            if(node == null)
               return 0;
    //递归的边界条件 如果当前节点是叶子节点(左右子树都为null),高度是1
            if(node.left == null && node.right == null){
                return 1;
            }
    //否则 左右节点有值 当前节点高度(只看当前节点)为1+ 那个不为null的子树的高度,因此为max      
            if(node.left == null || node.right == null){
                return 1 + Math.max(run(node.left), run(node.right));
            }
            //最后是都不为空 1+左右子树的最小高度
            return 1 + Math.min(run(node.left), run(node.right));
        }
    }
    

     另一种非递归的方法是层序遍历,从根节点开始,从上往下,利用一个队列存放需要遍历的节点,

    代码:

    public int run(TreeNode root) {
    
            if(root ==null)
                return 0;
            Queue<TreeNode> queue = new LinkedList<>();
            queue.offer(root);
    
            int depth = 0;//当前树的深度
            while(!queue.isEmpty()){
                int size = queue.size(); //这个地方是关键,获取当前层需要遍历的节点个数
    
                for(int i = 0; i < size; i++){
                    TreeNode current = queue.poll();
                    if(current.left == null && current.right == null) //如果左右子树都为空
                        return 1 + depth;
                    if(current.left != null){
                        queue.offer(current.left);
                    }
                    if(current.right != null){
                        queue.offer(current.right);
                    }
                }
                depth++;
            }
            return depth;
        }
    

      

    欢迎关注Java流水账公众号
  • 相关阅读:
    CentOS进程资源占用高原因分析命令
    Centos下修改启动项和网络配置
    CentOS查看系统信息命令和方法
    [vim]设置vim语法高亮显示和自动缩进
    [vim]vim中有中文乱码
    setState回调
    服务器安装nginx
    小程序map
    后台合成图片
    阿里云服务器添加nginx
  • 原文地址:https://www.cnblogs.com/guofu-angela/p/11456700.html
Copyright © 2011-2022 走看看