您的位置:首页 > 其它

leetcode | Minimum Depth of Binary Tree

2015-07-03 15:12 351 查看
rMinimum Depth of Binary Tree : https://leetcode.com/problems/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.

解析:

求最短路径上节点的个数。和求树的深度类似,但求树的深度是,选择左右子树中深度大的加 1,

最短路径(最小深度)则是选择左右子树中深度小的加 1。

需要注意的是,空节点不算叶节点,所以遇到空节点子树时,需要返回另一颗子树的深度加 1;在求树的深度时,选的是深度较大的一个,故不需考虑空节点子树

如:[1 2 NULL] 返回 2

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/

//定义:NULL不是叶节点
class Solution {
public:
int minDepth(TreeNode* root) {
if (root == NULL)
return 0;
if (root->left == NULL) // 左子树没有叶节点
return minDepth(root->right)+1;
if (root->right == NULL) // 右子树没有叶节点
return minDepth(root->left)+1;
return min(minDepth(root->left), minDepth(root->right)) + 1;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: