LeetCode刷题(C++)——Minimum Depth if Binary Tree(Easy)
题目描述
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.
/*
Definition for binary tree
struct TreeNode
{
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int x):val(x),left(NULL),right(NULL){}
};
*/
class Solution {
public:
int getDepth(TreeNode* p)
{
if (p == NULL)
return 0;
if (p->left == NULL&&p->right == NULL)
return 1;
int LD = INT_MAX;
int RD = INT_MAX;
if (p->left)
LD = getDepth(p->left)+1;
if (p->right)
RD = getDepth(p->right)+1;
return (LD > RD) ? RD : LD;
}
int run(TreeNode *root) {
int mindepth = getDepth(root);
return mindepth;
}
};
还没有评论,来说两句吧...