# 【LeetCode刷题日记】[104. 二叉树的最大深度]

## 二、解析

C++

class Solution {

public:
int maxDepth(TreeNode* root) {

if (root == nullptr) return 0;
return max(maxDepth(root->left), maxDepth(root->right)) + 1;
}
};

C

int maxDepth(struct TreeNode *root) {

if (root == NULL) return 0;
return fmax(maxDepth(root->left), maxDepth(root->right)) + 1;
}

C++

class Solution {

public:
int maxDepth(TreeNode* root) {

if (root == nullptr) return 0;
queue<TreeNode*> Q;
Q.push(root);
int ans = 0;
while (!Q.empty()) {

int sz = Q.size();
while (sz > 0) {

TreeNode* node = Q.front();Q.pop();
if (node->left) Q.push(node->left);
if (node->right) Q.push(node->right);
sz -= 1;
}
ans += 1;
}
return ans;
}
};

C

struct QueNode {

struct TreeNode *p;
struct QueNode *next;
};

void init(struct QueNode **p, struct TreeNode *t) {

(*p) = (struct QueNode *)malloc(sizeof(struct QueNode));
(*p)->p = t;
(*p)->next = NULL;
}

int maxDepth(struct TreeNode *root) {

if (root == NULL) return 0;
struct QueNode *left, *right;
init(&left, root);
right = left;
int ans = 0, sz = 1, tmp = 0;
while (left != NULL) {

tmp = 0;
while (sz > 0) {

if (left->p->left != NULL) {

init(&right->next, left->p->left);
right = right->next;
tmp++;
}
if (left->p->right != NULL) {

init(&right->next, left->p->right);
right = right->next;
tmp++;
}
left = left->next;
sz--;
}
sz += tmp;
ans++;
}
return ans;
}