1. 递归解法
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
int leftLen = 1 + maxDepth(root->left);
int rightLen = 1 + maxDepth(root->right);
return max(leftLen, rightLen);
}
};
更好的递归解法如下,能复用求树的最小深度的代码,把min函数改为max函数即可。
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
if(!root->right) return 1 + maxDepth(root->left);
if(!root->left) return 1 + maxDepth(root->right);
return 1 + max(maxDepth(root->left), maxDepth(root->right));
}
};
2. 迭代解法
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int maxDepth = 0;
queue<TreeNode*> que;
que.push(root);
while (!que.empty()) {
maxDepth++;
for (int i = que.size(); i > 0; i--) {
TreeNode *p = que.front();
que.pop();
if (p->left) que.push(p->left);
if (p->right) que.push(p->right);
}
}
return maxDepth;
}
};