方法一:递归
class Solution {
public:
int maxDepth(TreeNode* root) {
int height = 0;
if (root == NULL) {
return height;
} else {
int height1 = maxDepth(root->left) + 1;
int height2 = maxDepth(root->right) + 1;
height = height1 > height2 ? height1 : height2;
return height;
}
}
};
方法二:迭代法
class Solution {
public:
int maxDepth(TreeNode* root) {
queue<TreeNode*> que;
if (root != nullptr) {
que.push(root);
}
int depth = 0;
while (!que.empty()) {
int size = que.size();
depth++;
for (int i = 0; i < size; i++) {
TreeNode* node = que.front();
que.pop();
if (node->left) que.push(node->left);
if (node->right) que.push(node->right);
}
}
return depth;
}
};
class Solution {
public:
int maxDepth(Node* root) {
queue<Node*> que;
if (root != NULL) {
que.push(root);
}
int depth = 0;
while (!que.empty()) {
int size = que.size();
depth++;
for (int i = 0; i < size; i++) {
Node* node = que.front();
que.pop();
for (auto a : node->children) {
if (a) {
que.push(a);
}
}
}
}
return depth;
}
};
层序遍历yysd