Solution 1
实际上就是之前 0102. Binary Tree Level Order Traversal 里面“一层一层算”的思路。所以,使用BFS就可以了,完成一层就+1。
- 时间复杂度: O ( N ) O(N) O(N),其中 N N N为输入序列的节点个数,线性遍历处理输入
- 空间复杂度: O ( 2 ⌊ log N ⌋ ) O(2^{\lfloor \log N \rfloor}) O(2⌊logN⌋),其中 N N N为输入序列的节点个数,因为最坏情况下,最后一层全满,整个队列最大占用就是最后一层
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
int maxDepth(TreeNode* root) {
int ans = 0;
if (root != nullptr) {
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int numNodeLevel = q.size();
while (numNodeLevel--) {
auto now = q.front();
q.pop();
auto left = now->left;
if (left != nullptr) {
q.push(left);
}
auto right = now->right;
if (right != nullptr) {
q.push(right);
}
}
ans++;
}
}
return ans;
}
};
Solution 2
Solution 1的Python实现
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
ans = 0
if root is not None:
q = collections.deque([root])
while q:
numNodeLevel = len(q)
while numNodeLevel:
now = q.popleft()
left, right = now.left, now.right
if left is not None:
q.append(left)
if right is not None:
q.append(right)
numNodeLevel -= 1
ans += 1
return ans