LeetCode 111. Minimum Depth of Binary Tree

来源:互联网 发布:淘宝加盟店 编辑:程序博客网 时间:2024/06/11 01:45

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.

叶子节点是没有子节点的节点,刚开始没有理解这句话。所以对于测试用例[1,2],返回了1,应该是2 。 希望大家注意。

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    int length = 0;    int minLength = 0;    public int minDepth(TreeNode root) {        if(root == null){            return 0;        }        if(root.left == null){            return 1 + minDepth(root.right);        }        if(root.right == null){            return 1+ minDepth(root.left);        }        return 1 + Math.min(minDepth(root.left),minDepth(root.right));    }}

时间复杂度O(n), n为节点个数, 空间复杂度为O(1)。

0 0
原创粉丝点击