给定一个二叉树,找出其最小深度。
最小深度是从根节点到最近叶子节点的最短路径上的节点数量。
说明: 叶子节点是指没有子节点的节点。
我的思路就是遍历二叉树。找到叶子节点的深度,然后排序,输出最小值即可
/**
* 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:
void min(TreeNode*root,vector<int> & res,int dep){
if(root==NULL) return ;
if(root->left==NULL&&root->right==NULL) res.push_back(dep);
min(root->left,res,dep+1);
min(root->right,res,dep+1);
}
int minDepth(TreeNode* root) {
if(root==NULL) return 0;
vector<int> res;
min(root,res,1);
sort(res.begin(),res.end());
return res[0];
}
};
AC 利用的是递归的自加性。 简洁舒服
class Solution {
public:
int minDepth(TreeNode* root) {
if (!root)
return 0;
int ld = minDepth(root->left);
int rd = minDepth(root->right);
if (ld > 0 && rd > 0) {
if (ld < rd)
return ld + 1;
else
return rd + 1;
}
else if (ld > 0)
return ld + 1;
else
return rd + 1;
}
};