zoukankan      html  css  js  c++  java
  • 二叉树的最小深度

    Leetcode题目描述

    给定一个二叉树,找出其最小深度。

    最小深度是从根节点到最近叶子节点的最短路径上的节点数量。

    说明: 叶子节点是指没有子节点的节点。

    示例:

    给定二叉树 [3,9,20,null,null,15,7],

        3
       / 
      9  20
        /  
       15   7
    

    返回它的最小深度 2.

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/minimum-depth-of-binary-tree

    深度优先解答

    题目特点很明显,而且也很简单。

    只需要分别判断根节点左右两个节点的距离距离叶节点的深度,取左右两个节点的最小深度加1即可。

    依次递归,既可以求出结果

    深度优先Demo

    class Solution {
        public int minDepth(TreeNode root) {
            if (root == null) {
                return 0;
            }
    
            if (root.left == null && root.right == null) {
                return 1;
            }
    
            int min_depth = Integer.MAX_VALUE;
            if (root.left != null) {
                min_depth = Math.min(minDepth(root.left), min_depth);
            }
            if (root.right != null) {
                min_depth = Math.min(minDepth(root.right), min_depth);
            }
    
            return min_depth + 1;
        }
    }
    
    
  • 相关阅读:
    windows10装机小记
    Linus Benedict Torvalds hate FUD
    营销文章good
    商城趣聊4
    商城趣聊3
    商城趣聊2
    商城趣聊1
    temp
    学习代码检视方法 (摘自某图片)
    xilinx sdk闪退问题
  • 原文地址:https://www.cnblogs.com/Di-iD/p/13784898.html
Copyright © 2011-2022 走看看