0
点赞
收藏
分享

微信扫一扫

[LeetCode]Minimum Depth of Binary Tree


Question
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.

本题难度Easy。

递归

【复杂度】
时间 O(N) 空间 O(N)

【思路】
当求最大深度时,我们只要在左右子树中取较大的就行了,然而最小深度时,如果左右子树中有一个为空会返回0,这时我们是不能算做有效深度的。所以分成了三种情况,左子树为空,右子树为空,左右子树都不为空。当然,如果左右子树都为空的话,就会返回1。

【代码】

/**
* 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) {
//base case
if(root==null){
return 0;
}
//invariant
int left=minDepth(root.left);
int right=minDepth(root.right);
//ensure
if(left==0&&right==0)
return 1;
else if(left==0&&right>0)
return right+1;
else if(right==0&&left>0)
return left+1;
else
return Math.min(left,right)+1;
}
}

参考

​​[Leetcode] Maximum and Minimum Depth of Binary Tree 二叉树的最小最大深度​​


举报

相关推荐

0 条评论