题目描述
题解
使用递归,二叉树的最大深度是其左子树和右子树最大深度的最大值再加一
C++中得到两个数a和b中的最大值可以直接使用max(a, b)
代码
// maxDepth.cpp
#include <iostream>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x): val(x), left(NULL), right(NULL){}
~TreeNode(){
if (this->left != NULL){
delete this->left;
this->left = NULL;
}
if (this->right != NULL){
delete this->right;
this->right = NULL;
}
}
};
class Solution {
public:
/**
*
* @param root TreeNode类
* @return int整型
*/
int maxDepth(TreeNode* root) {
// write code here
if (root == NULL){
return 0;
}
else{
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
}
};
int main(){
TreeNode* root = new TreeNode(1);
root->left = new TreeNode(2);
Solution s;
cout << s.maxDepth(root) << endl;
delete root;
return 0;
}