您的位置:首页 > 其它

【LeetCode练习题】Minimum Depth of Binary Tree

2014-04-13 16:31 399 查看


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 0;
int l = minDepth(root->left);
int r = minDepth(root->right);
if(l * r != 0)
return min(l,r)+1;
else if(l == 0)
return r+1;
else
return l+1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: