二叉树的深度
原创大约 1 分钟
题目:
输入一棵二叉树的根节点,求该树的深度。从根节点到叶节点依次经过的节点(含根、叶节点)形成树的一条路径,最长路径的长度为树的深度。
示例
输入: 给定二叉树 [3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回它的最大深度 3 。思考:
提示
树的遍历方式分为:深度优先搜索(DFS)和 广度优先搜索(BFS)
深度优先可以使用递归实现
此时,树的深度 等于 左子树的深度 与 右子树的深度 中的 最大值 +1
题解:
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
return Math.max(maxDepth(root.left),maxDepth(root.right)) + 1;
}
}提示
也可以使用广度优先搜索,此时需要借助辅助队列
每遍历一层,结果加一
class Solution {
public int maxDepth(TreeNode root) {
if (root == null) return 0;
int res = 0;
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while (!queue.isEmpty()){
res++;
int n = queue.size();
for (int i = n; i > 0; i--) {
TreeNode node = queue.poll();
if (node.left != null) queue.add(node.left);
if (node.right != null) queue.add(node.right);
}
}
return res;
}
}