文章目录
题目描述
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
例如:
给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。
题解思路
方法一:深度优先搜索(DFS)
我们找出 root 的左子树和右子树的深度,然后用其较大的值 +1 即可(因为 root 本身也有一个单位的深度)。
代码实现:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
int l = maxDepth(root->left);
int r = maxDepth(root->right);
return max(l, r) + 1;
}
};
方法二:广度优先搜索(BFS)
- 树的层序遍历 / 广度优先搜索往往利用 队列 实现。
- 关键点: 每遍历一层,则计数器 +1 ,直到遍历完成,则可得到树的深度。
代码实现:
class Solution {
public:
int maxDepth(TreeNode* root) {
if(!root) return 0;
queue<TreeNode*> bfs;
bfs.push(root);
int res = 0;
while (!bfs.empty()) {
// 第一层循环确保当前层还有元素
queue<TreeNode*> temp; // temp 用于储存当前层的下一层的所有元素
while (!bfs.empty()) {
// 第二层循环则是遍历当前层的所有元素
if (bfs.front()->left) {temp.push(bfs.front()->left);}
if (bfs.front()->right) {temp.push(bfs.front()->right);}
bfs.pop();
}
++ res; // 层数 +1
bfs = temp; // bfs 更新到当前层的下一层
}
return res;
}
};
如有帮助到您,可以多多点赞、评论鼓励哟~~~