LeetCode刷题(C++)——Maximum Depth of 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 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 getDepth(TreeNode* p)
{
if(p==NULL)
{
return 0;
}
int LD,RD;
LD = getDepth(p->left);
RD =getDepth(p->right);
return (LD>RD?LD:RD)+1;
}
int maxDepth(TreeNode* root) {
return getDepth(root);
}
};
一种更简便的实现方法
/**
* 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 maxDepth(TreeNode* root) {
return root? max(maxDepth(root->left),maxDepth(root->right))+1:0;
}
};
还没有评论,来说两句吧...