我的解题:
1.最喜欢用层次遍历,,,所以还是这个方法,queue里保存的是pair
queue<pair<TreeNode*,int>> q; int是所在的层数
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<pair<TreeNode*,int>> q;
if(!root) return 0;
q.push(make_pair(root,1));
int level=1;
while(!q.empty()){
auto [tmp,now]=q.front();
q.pop();
if(tmp==NULL) continue;
level=max(level,now);
q.push(make_pair(tmp->right,now+1));
q.push(make_pair(tmp->left,now+1));
}
return level;
}
};
2.递归
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return NULL;
return max(maxDepth(root->right),maxDepth(root->left))+1;
}
};