二叉树的深度为根节点到最远叶子节点的最长路径上的节点数。这道题求的是二叉树的最大深度,也就是二叉树的层数。可以使用层序遍历记录层数,最后返回最大层数。
时间复杂度:O(n),空间复杂度:O(n)
思路:
- 创建一个队列,如果不为空树,则将根节点(第一个节点)入队。
- 构建一个循环,循环终止条件为队列中没有需要处理的节点,即将树中全部节点处理完。每一次循环时,depth++。
- 再构建一个嵌套循环,用于处理当前层级的所有节点,循环终止条件是处理完当前级别的所有节点。
- 如果当前处理节点有左子节点,则将其放入队列中,在下一个大循环里作为下一层级的节点处理。右子节点同理。
- 大循环结束,返回层数depth。
代码:
/**
* 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) {
queue<TreeNode*> que;
int depth = 0;
if (root != nullptr)
que.push(root);
while (!que.empty()) {
int size = que.size();
depth++;
while (size--) {
TreeNode* node = que.front();
que.pop();
if (node->left)
que.push(node->left);
if (node->right)
que.push(node->right);
}
}
return depth;
}
};