55.1 二叉树的深度
题目描述
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
解题思路
树的深度等于左右子树深度的较大值加 1,空树的深度为 0。
public int calculateDepth(TreeNode root) {
return root == null ? 0 : 1 + Math.max(calculateDepth(root.left), calculateDepth(root.right));
}
从根结点到叶结点依次经过的结点(含根、叶结点)形成树的一条路径,最长路径的长度为树的深度。
树的深度等于左右子树深度的较大值加 1,空树的深度为 0。
public int calculateDepth(TreeNode root) {
return root == null ? 0 : 1 + Math.max(calculateDepth(root.left), calculateDepth(root.right));
}
在阅读器中可以用目录和搜索、切换深色模式、练习这篇笔记中的面试题:打开《55.1 二叉树的深度》