您的位置:首页 > 其它

LeetCode 111. Minimum Depth of Binary Tree

2017-04-09 11:22 309 查看
题目:

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,如果根节点只有左节点 ,返回 minDepth(root->left)+1;如果根节点只有右节点,返回minDepth(root->right)+1;如果都有,返回两个中小的。

代码:

/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int minDepth(TreeNode* root) {
if(NULL==root){//如果根节点为NULL,返回0
return 0;
}
else if(root->left==NULL&&root->right==NULL){//如果根节点没有叶节点,返回1
return 1;
}
else if(root->left!=NULL&&root->right==NULL){//如果根节点只有左节点
return minDepth(root->left)+1;
}
else if(root->left==NULL&&root->right!=NULL){//如果根节点只有右节点
return minDepth(root->right)+1;
}
else{//如果左右节点都有
return min(minDepth(root->left)+1,minDepth(root->right)+1);
}
}
};


**输出结果:**9ms
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: