zoukankan      html  css  js  c++  java
  • [leedcode 111] 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.

    /**
     * Definition for a binary tree node.
     * public class TreeNode {
     *     int val;
     *     TreeNode left;
     *     TreeNode right;
     *     TreeNode(int x) { val = x; }
     * }
     */
    public class Solution {
        public int minDepth(TreeNode root) {
            //注意考虑节点只有一个子节点是空的情况,此时应该舍弃空子树,一种方法,将其设为最大值,一种直接舍弃
       /*     if(root==null) return 0;
    
            if(root.left==null&&root.right==null) return 1;
    
    
            if(root.left==null) return minDepth(root.right)+1;
            if(root.right==null) return minDepth(root.left)+1;
            return Math.min(minDepth(root.left),minDepth(root.right))+1;*/
            
            
            if(root==null) return 0;
            int left=minDepth(root.left);
            int right=minDepth(root.right);
            if(root.left==null&&root.right==null) return 1;//root.left==null等价于left==0
            if(left==0) left=Integer.MAX_VALUE;
            if(right==0) right=Integer.MAX_VALUE;
            return Math.min(left,right)+1;
        }
    }
  • 相关阅读:
    工厂方法和抽象工厂
    waterMarkTextBox
    button hot key 热键
    wpf 双击行。。获得行信息
    update comboBox
    WPF标准控件模板查看程序(文件里面)
    Sp EF输出 临时表
    tree view
    Ubuntu 常用命令
    ESP8266 开发记录
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4667115.html
Copyright © 2011-2022 走看看