leetcode中Minimum Depth of Binary Tree 问题

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.

即寻找最短路径,例如下面的

java代码

/**
 * Definition for binary tree
 * 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+Math.min(minDepth(root.left),minDepth(root.right));
        if(root.left!=null&&root.right==null)
            return 1+minDepth(root.left);
        if(root.left==null&&root.right!=null)  
            return 1+minDepth(root.right);
        if(root.left==null&&root.right==null) 
            return 1;
        return 0;
    }
}

问题分析

      5
     / \
    4   8
   /   / \
  11  13  4
 /  \      \
7    2      1 

最小分支即为5-8-13,大小为3,即寻找两者中最小的