package main import . "nc_tools" import ( "math" ) /* * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */ /** * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可 * * * @param root TreeNode类 * @return int整型 */ func maxDepth(root *TreeNode) int { // write code here // 2. 递归终止条件:节点为空,深度为0 if root == nil { return 0 } // 1. 问题分解(递推公式) // 1.1 获取左子树的深度 leftMax := maxDepth(root.Left) // 1.2 获取右子树的深度 rightMax := maxDepth(root.Right) // 左右子树的最大值 maxValue := int(math.Max(float64(leftMax), float64(rightMax))) // 1.3 返回:左右子树深度的最大值+1(当前节点) return maxValue + 1 }