解题思路
一个递归解决,这里注意一下问题分类:
- 根节点为 null ,深度为 0
- 左节点且右节点为 null,深度为 1
- 其他情况,看左右子节点哪个的深度大,再加个 1 就是自己到最远叶子节点的深度,倒推回去就是整棵树的最大深度
/**
* Definition for a binary tree node.
* class TreeNode(var _value: Int) {
* var value: Int = _value
* var left: TreeNode = null
* var right: TreeNode = null
* }
*/
object Solution {
def maxDepth(root: TreeNode): Int = {
if(root ==null) 0
else if(root.left ==null &&
root.right==null) 1
else max(maxDepth(root.left), maxDepth(root.right)) + 1
}
def max(x:Int, y:Int):Int = {
if(x>=y) x
else y
}
}