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;
        }
    }
  • 相关阅读:
    肥胖儿筛选标准
    文章索引
    面向对象66原则
    [精]Xpath路径表达式
    [精]XPath入门教程
    孕产期高危因素
    “华而不实”的转盘菜单(pie menu)
    xmind用例导excel用例,然后再用python排版
    NSObject
    [self class]与[super class]
  • 原文地址:https://www.cnblogs.com/qiaomu/p/4667115.html
Copyright © 2011-2022 走看看