标签:注意 地址 二叉树 tree node 最大值 返回 diameter 题目 变量
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
示例 : 给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
遍历每一个节点,计算每个节点最大直径(左子树深度+右子树深度),更新全局变量ans。
/go
//* Definition for a binary tree node.
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var ans = 0
func diameterOfBinaryTree(root *TreeNode) int {
ans = 0
if root == nil {
return 0
}
maxDepth(root)
return ans
}
// 节点node的最大深度
func maxDepth(node *TreeNode) int {
if node == nil {
return 0
}
lhight := maxDepth(node.Left)
rhight := maxDepth(node.Right)
ans = max(ans, lhight+rhight) //将每个节点最大直径(左子树深度+右子树深度)当前最大值比较并取大者
return max(lhight, rhight)+1 //返回节点深度
}
func max(x int, y int) int {
if x > y {
return x
}else {
return y
}
}
地址:https://mp.weixin.qq.com/s/x2YQXBcjMd9gNuK8qNRSCw
标签:注意 地址 二叉树 tree node 最大值 返回 diameter 题目 变量
原文地址:https://www.cnblogs.com/smallleiit/p/13437686.html