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流水账公众号
  • 相关阅读:
    简述 JPA 与 Spring Data JPA 与 Hibernate
    idea不识别yml配置文件,怎么办?
    Java 数组如何转成List集合
    git关于 LF 与 CRLF
    git报错:src refspec master does not match any
    蓝桥杯- 基础练习:十六进制转八进制
    蓝桥杯- 基础练习:数列排序
    蓝桥杯-入门训练 :A+B问题
    蓝桥杯-入门训练 :序列求和
    蓝桥杯-入门训练 :圆的面积
  • 原文地址:https://www.cnblogs.com/guofu-angela/p/11456700.html
Copyright © 2011-2022 走看看