您的位置:首页 > 其它

LeetCode(111) Minimum Depth of Binary Tree

2015-10-18 13:09 316 查看

题目

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.

分析

求二叉树的最小深度:根节点到最近叶子节点的路径长度。

同样采用递归的思想:

当根节点为空,返回0;

当根节点为唯一的二叉树节点时,返回1;

否则,求解并返回 最小(非空,保证最终到达叶节点)左右子树深度 + 1;

AC代码

class Solution {
public:
int minDepth(TreeNode* root) {
if (!root)
return 0;
//独立的根节点
else if (!root->left && !root->right)
return 1;
else{
int left_depth, right_depth;
if (root->left)
left_depth = minDepth(root->left);
else
left_depth = INT_MAX;
if (root->right)
right_depth = minDepth(root->right);
else
right_depth = INT_MAX;
return min(left_depth, right_depth) + 1;
}

}
};


GitHub测试程序源码
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: