leetbook_ioa/docs/LCR 175. 计算二叉树的深度.md
树的遍历方式总体分为两类:
求树的深度需要遍历树的所有节点,本文将介绍基于 后序遍历(DFS) 和 层序遍历(BFS) 的两种解法。
树的后序遍历 / 深度优先搜索往往利用 递归 或 栈 实现,本文使用递归实现。
关键点: 此树的深度和其左(右)子树的深度之间的关系。显然,此树的深度 等于 左子树的深度 与 右子树的深度 中的 最大值 $+1$ 。
{:align=center width=450}
root 为空,说明已越过叶节点,因此返回 深度 $0$ 。root 的 左子树的深度 ,即调用 calculateDepth(root.left);root 的 右子树的深度 ,即调用 calculateDepth(root.right);max(calculateDepth(root.left), calculateDepth(root.right)) + 1。<,,,,,,,,,>
class Solution:
def calculateDepth(self, root: TreeNode) -> int:
if not root: return 0
return max(self.calculateDepth(root.left), self.calculateDepth(root.right)) + 1
class Solution {
public int calculateDepth(TreeNode root) {
if(root == null) return 0;
return Math.max(calculateDepth(root.left), calculateDepth(root.right)) + 1;
}
}
class Solution {
public:
int calculateDepth(TreeNode* root) {
if(root == nullptr) return 0;
return max(calculateDepth(root->left), calculateDepth(root->right)) + 1;
}
};
树的层序遍历 / 广度优先搜索往往利用 队列 实现。
关键点: 每遍历一层,则计数器 $+1$ ,直到遍历完成,则可得到树的深度。
root 为空,直接返回 深度 $0$ 。queue (加入根节点 root ),计数器 res = 0。queue 为空时跳出。
tmp ,用于临时存储下一层节点;queue 中的各节点 node ,并将其左子节点和右子节点加入 tmp;queue = tmp ,将下一层节点赋值给 queue;res += 1 ,代表层数加 $1$;res 即可。<,,,,,>
class Solution:
def calculateDepth(self, root: TreeNode) -> int:
if not root: return 0
queue, res = [root], 0
while queue:
tmp = []
for node in queue:
if node.left: tmp.append(node.left)
if node.right: tmp.append(node.right)
queue = tmp
res += 1
return res
class Solution {
public int calculateDepth(TreeNode root) {
if(root == null) return 0;
List<TreeNode> queue = new LinkedList<>() {{ add(root); }}, tmp;
int res = 0;
while(!queue.isEmpty()) {
tmp = new LinkedList<>();
for(TreeNode node : queue) {
if(node.left != null) tmp.add(node.left);
if(node.right != null) tmp.add(node.right);
}
queue = tmp;
res++;
}
return res;
}
}
class Solution {
public:
int calculateDepth(TreeNode* root) {
if(root == nullptr) return 0;
vector<TreeNode*> que;
que.push_back(root);
int res = 0;
while(!que.empty()) {
vector<TreeNode*> tmp;
for(TreeNode* node : que) {
if(node->left != nullptr) tmp.push_back(node->left);
if(node->right != nullptr) tmp.push_back(node->right);
}
que = tmp;
res++;
}
return res;
}
};
queue 同时存储 $N/2$ 个节点。