【LeetCode练习题】Minimum Depth of Binary Tree

时间:2022-01-01 11:32:22

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.

和上一题对应,求二叉树的最小深度。

解题思路:

参考上一题Maximun Depth of Binary Tree中最后那个极短的解法。

另外需要判断一下递归返回0的时候的结果不可取,因为不是叶节点。

代码如下:

class Solution {
public:
int minDepth(TreeNode *root) {
if(!root)
return ;
int l = minDepth(root->left);
int r = minDepth(root->right);
if(l * r != )
return min(l,r)+;
else if(l == )
return r+;
else
return l+;
}
};