牛客题霸 NC6 二叉树的最大路径和
生活随笔
收集整理的這篇文章主要介紹了
牛客题霸 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 }參考文章
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
以上是生活随笔為你收集整理的牛客题霸 NC6 二叉树的最大路径和的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 牛客题霸 NC5 二叉树根节点到叶子节点
- 下一篇: 牛客题霸 NC7 买卖股票的最好时机