求给定二叉树的最大深度,
最大深度是指树的根结点到最远叶子结点的最长路径上结点的数量。
思路:递归调用,获取左右节点的深度,取最大值+1作为当前节点的深度.
package main
import . "nc_tools"
/*
* type TreeNode struct {
* Val int
* Left *TreeNode
* Right *TreeNode
* }
*/
/**
*
* @param root TreeNode类
* @return int整型
*/
func maxDepth( root *TreeNode ) int {
// write code here
return GetDepth(root)
}
func GetDepth(root *TreeNode) int {
if root == nil {
return 0
}
depth := 0
leftDepth := GetDepth(root.Left)
rightDepth := GetDepth(root.Right)
depth = leftDepth + 1
if rightDepth > leftDepth {
depth = rightDepth + 1
}
return depth
}
这篇博客介绍了如何计算给定二叉树的最大深度。通过递归实现,遍历树的每个节点,分别获取左子树和右子树的深度,然后取较大值加一作为当前节点的深度。这种方法可以有效地找出从根节点到最远叶子节点的最长路径。
229

被折叠的 条评论
为什么被折叠?



