Leetcode-标签为Tree 111. Minimum Depth of Binary Tree

来源:互联网 发布:2200万淘宝买家资料 编辑:程序博客网 时间:2024/06/18 12:49

原题

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.

题目分析

求最小深度。注意是从根到叶子的最小距离

代码实现

public class Solution {    public int MinDepth(TreeNode root) {        if(root==null)           return 0;        if(isLeaf(root))           return 1;        if(root.left==null)           return 1 + MinDepth(root.right);        if(root.right ==null)           return 1 + MinDepth(root.left);        return Math.Min(MinDepth(root.left),MinDepth(root.right))+1;    }    private bool isLeaf(TreeNode node)    {        return node.left==null && node.right==null;    }}
2 0
原创粉丝点击