Maximum Path Sum in Binary Tree
二叉树中和最大的轨迹
问题描述
给定一个二叉树,找到两个结点之间最大和,两个结点之间的轨迹不一定经过根节点。
测试样例
# Input:
10
/ \
2 10
/ \ \
20 1 -25
/ \
3 4
# Output:
42
# 结点 20 + 2 + 10 + 10
内容首发于微信公众号IT信息教室,如果您想学习更多AI相关的技能,欢迎搜索关注或微信扫描下方二维码关注~~
参考代码
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# ---------------------
# O(n) time, O(1) space.
# ---------------------
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
# 使用递归的方法,有三种情况
# 1. 最大路径包含根节点
# 2. 最大路径在左子树里
# 3. 最大路径在右子树里
def maxPathSum(root):
def helper(root):
if root is None:
return (float('-inf'), 0)
leftMaxSum, leftPath = helper(root.left)
rightMaxSum, rightPath = helper(root.right)
# 计算经过根节点的最大路径
rootMaxSum = max(0, leftPath) + root.value + max(0, rightPath)
# 找到最大路径(可能包含或者不包含根节点)
maxSum = max(leftMaxSum, rootMaxSum, rightMaxSum)
# 找到以根节点结尾的最大路径
rootPath = max(leftPath, rightPath, 0) + root.value
return (maxSum, rootPath)
return helper(root)[0]
# Test Program
# (* 表示最大轨迹)
# *10
# / \
# *2 *10
# / \ \
# *20 1 -25
# / \
# 3 4
root = Node(10)
root.left = Node(2)
root.right = Node(10)
root.left.left = Node(20)
root.left.right = Node(1)
root.right.right = Node(-25)
root.right.right.left = Node(3)
root.right.right.right = Node(4)
print(maxPathSum(root))
# 42