每日一题-20200728

题目

给定一个二叉树,返回树深

解答

递归解决,取左子树,右子树中的最大高度 + 1 即为所求结果

1
2
3
4
5
6
7
8
9
object Solution {
def maxDepth(root: TreeNode): Int = {
if (root == null) { 0 }
else {
math.max(maxDepth(root.left), maxDepth(root.right)) + 1
}

}
}

时间复杂度分析:O(n),每个节点都遍历一次
空间复杂度分析:O(height),递归需要栈空间,栈空间取决于递归的深度。

使用搜索:谷歌必应百度