牛客题霸 NC6 二叉树的最大路径和

https://www.nowcoder.com/practice/da785ea0f64b442488c125b441a4ba4a

解决方案

Go

var res int = -1e10func maxPathSum(root *TreeNode) int {// write code heregetMaxPathSum(root)return res
}func getMaxPathSum(root *TreeNode) int {if root == nil {return 0}leftMax := max(0, getMaxPathSum(root.Left))rightMax := max(0, getMaxPathSum(root.Right))res = max(res, root.Val+max(leftMax+rightMax, max(leftMax, rightMax)))return max(leftMax, rightMax) + root.Val
}func max(a, b int) int {if a > b {return a}return b
}

参考文章


本文来自互联网用户投稿,文章观点仅代表作者本人,不代表本站立场,不承担相关法律责任。如若转载,请注明出处。 如若内容造成侵权/违法违规/事实不符,请点击【内容举报】进行投诉反馈!

相关文章

立即
投稿

微信公众账号

微信扫一扫加关注

返回
顶部