zoukankan      html  css  js  c++  java
  • Leetcode-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.

    Solution:

     1 /**
     2  * Definition for binary tree
     3  * public class TreeNode {
     4  *     int val;
     5  *     TreeNode left;
     6  *     TreeNode right;
     7  *     TreeNode(int x) { val = x; }
     8  * }
     9  */
    10 public class Solution {
    11     public int minDepth(TreeNode root) {
    12         if (root==null) return 0;
    13         int res = minDepthRecur(root,0);
    14         return res;
    15     }
    16     
    17     public int minDepthRecur(TreeNode curNode, int curDepth){
    18         if (curNode.left==null&&curNode.right==null){
    19             return curDepth+1;
    20         }
    21         
    22         int left = Integer.MAX_VALUE;
    23         int right = Integer.MAX_VALUE;
    24         if (curNode.left!=null)
    25             left = minDepthRecur(curNode.left, curDepth+1);
    26         if (curNode.right!=null)
    27             right = minDepthRecur(curNode.right,curDepth+1);
    28         
    29         if (left<right)
    30             return left;
    31         else
    32             return right;
    33     }
    34 }

    This is a easy recursive problem.

  • 相关阅读:
    设计模式之装饰者模式
    每天一点点
    生财有道
    地图的移动和缩放
    钱分割
    位运算
    ref和out
    使用startCoroutine制定倒计时
    静态类和单例类
    Awake和Start
  • 原文地址:https://www.cnblogs.com/lishiblog/p/4083103.html
Copyright © 2011-2022 走看看