104. 二叉树的最大深度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
//! bfs写法,用队列写bfs n,n->时间上每个元素入队出队一次,共2n次;空间上如果为完全二叉树,队列最长n/2
class Solution {
public:
int maxDepth(TreeNode *root) {
if (root == nullptr) {
return 0;
}
TreeNode *node = root;
int res = 0;
queue<TreeNode *> treeQueue;
treeQueue.push(node);
while (!treeQueue.empty()) {
res += 1;
int levelSize = treeQueue.size();
for (int i = 0; i < levelSize; ++i) {
node = treeQueue.front();
treeQueue.pop();
if (node->left != nullptr) {
treeQueue.push(node->left);
}
if (node->right != nullptr) {
treeQueue.push(node->right);
}
}
}
return res;
}
};