LeetCode 104. 二叉树的最大深度(二叉树基础之——二叉树的深度)
程序员文章站
2022-05-20 20:24:00
...
DFS:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
return 1+max(maxDepth(root->left),maxDepth(root->right));
}
};
BFS:
/**
* 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) {
int layer = 0;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()){
int size = q.size();
while(size--){
TreeNode* r = q.front();
q.pop();
if(!r){
continue;
}
q.push(r->left);
q.push(r->right);
}
layer++;
}
return layer-1;
}
};