104. 二叉树的最大深度 - 力扣(LeetCode)
1、用层序遍历,一层层遍历
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)
return 0;
vector<TreeNode*> que;
que.push_back(root);
int res = 0;//记层数
while(!que.empty())
{
vector<TreeNode*> tmp;
for(TreeNode* node : que)
{
if(node->left != nullptr)
tmp.push_back(node->left);
if(node->right != nullptr)
tmp.push_back(node->right);
}
res++;
que = tmp;
}
return res;
}
};
2、用最大深度
mapDepth()
class Solution {
public:
int maxDepth(TreeNode* root) {
if(root == nullptr)
return 0;
return max(maxDepth(root->left),maxDepth(root->right)) + 1;
}
};