1 DFS
代码语言:javascript
复制/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
int max_depth = max(maxDepth(root->left), maxDepth(root->right));
return max_depth 1;
}
};
2 BFS
代码语言:javascript
复制class Solution {
public:
int maxDepth(TreeNode* root) {
if (!root) return 0;
queue<TreeNode*> q;
q.push(root);
int depth = 0;
while (!q.empty()) {
int sz = q.size();
for (int i=0;i < sz;i ) {
TreeNode* e_ptr = q.front(); q.pop();
if (e_ptr->left) q.push(e_ptr->left);
if (e_ptr->right) q.push(e_ptr->right);
}
depth ;
}
return depth;
}
};