思路
二叉树常见的递归方案
code
type TreeNode struct {
Val int
Left *TreeNode
Right *TreeNode
}
var ans int
func longestUnivaluePath(root *TreeNode) int {
ans = 0
longestPath(root)
return ans
}
func longestPath(root *TreeNode) int {
if root == nil {
return 0
}
l := longestPath(root.Left)
r := longestPath(root.Right)
pl, pr := 0, 0
if root.Left != nil && root.Val == root.Left.Val {
pl = l + 1
}
if root.Right != nil && root.Val == root.Right.Val {
pr = r + 1
}
ans = mymax(ans, pl+pr)
return mymax(pl, pr)
}
func mymax(x, y int) int {
if x > y {
return x
}
return y
}
更多内容请移步我的repo:https://github.com/anakin/golang-leetcode
本文介绍了一种解决二叉树中最长相同路径问题的递归算法。通过定义树节点结构,实现了一个名为longestUnivaluePath的函数,该函数能够找出二叉树中具有相同值的最长路径长度。算法利用了深度优先搜索策略,递归地检查每个子树的最长相同路径,并更新全局变量ans来记录最长路径。

1843

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



