您的位置:首页 > 其它

[LeetCode] Minimum Depth of Binary Tree

2014-11-13 09:51 357 查看
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.

我记得有一题是叫算Max depth 的,如出一辙。思路就是拿到一颗树,分别算出他左右子树的min depth,然后返回其中最小的那个+1就行了。

但是要注意的是和max depth有区别的地方在于,要判断左右子树存不存在先,如果不存在就忽略了。

int minDepth(TreeNode *root) {
if (!root) return 0;
if (!root->left && !root->right) return 1;

int leftMin = INT_MAX;
int rightMin = INT_MAX;

if (root->left)
leftMin = minDepth(root->left);
if (root->right)
rightMin = minDepth(root->right);

return leftMin < rightMin ? leftMin+1 : rightMin+1;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: