题解 | 二叉树中的最大路径和

二叉树中的最大路径和

https://www.nowcoder.com/practice/8fda1d22554f4824b0ef9c26f35e54dd

import sys

sys.setrecursionlimit(1 << 25)
# for line in sys.stdin:
#     a = line.split()
#     print(int(a[0]) + int(a[1]))

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def build_tree(n, values, parents):
    nodes = [None] * (n + 1)  # 节点编号从1到n
    for i in range(1, n+1):
        nodes[i] = TreeNode(values[i-1])
    
    root = None
    for i in range(1, n+1):
        parent = parents[i-1]
        if parent == 0:
            root = nodes[i]
            continue
        parent_node = nodes[parent]
        if parent_node.left is None:
            parent_node.left = nodes[i]
        else:
            parent_node.right = nodes[i]
    return root

class Solution:
    def maxPathSum(self, root):
        self.max_sum = float('-inf')
        def dfs(node):
            if not node:
                return 0
            left_gain = max(dfs(node.left), 0)
            right_gain = max(dfs(node.right), 0)
            current_sum = node.val + left_gain + right_gain
            self.max_sum = max(self.max_sum, current_sum)
            return node.val + max(left_gain, right_gain)
        dfs(root)
        return self.max_sum

# 读取输入并执行
n = int(input())
values = list(map(int, input().split()))
parents = list(map(int, input().split()))
root = build_tree(n, values, parents)
solution = Solution()
print(solution.maxPathSum(root))




全部评论

相关推荐

码农索隆:有点耳熟,你们是我教过最差的一届
点赞 评论 收藏
分享
07-02 18:09
门头沟学院 Java
苍穹外卖和谷粒商城这俩是不是烂大街了,还能做吗?
想去重庆的鸽子在吐槽:你不如把这俩做完自己搞明白再优化点再来问 何必贩卖焦虑
点赞 评论 收藏
分享
机械打工仔:我来告诉你原因,是因为sobb有在线简历,有些HR为了快会直接先看在线简历,初步感觉不合适就不会找你要详细的了
投了多少份简历才上岸
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务