您的位置:首页 > 其它

LeetCode——minimum-depth-of-binary-tree 二叉树的最小深度

2019-04-07 15:05 316 查看

LeetCode——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.
题目分析:
深度和广度皆可。深度用递归,广度用队列实现。
下面代码用深度搜索,递归实现
AC代码:

class Solution {
public:
int run(TreeNode *root) {
if(root==NULL)//空树返回0
return 0;
if(root->left&&root->right)//如果有左右孩子,返回左右子树的最小深度+1
return min(run(root->left),run(root->right))+1;
else if(root->left)//如果只有左孩子,返回左子树深度+1
return run(root->left)+1;
else if(root->right)//如果只有右孩子,返回右子树深度+1
return run(root->right)+1;
else return 1;//只有根节点,没有左右孩子返回1
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: