이진 트리가 있다고 가정합니다. 두 노드 사이의 모든 경로의 최대 합을 찾아야 합니다.
따라서 입력이 다음과 같으면

노드가 [12,13,14,16,7]이므로 출력은 62가 됩니다.
이 문제를 해결하기 위해 다음 단계를 따릅니다. −
-
utils() 함수를 정의합니다. 이것은 뿌리를 내릴 것입니다
-
루트가 null이면
-
0 반환
-
-
l :=utils(루트 왼쪽)
-
r :=utils(루트 오른쪽)
-
max_single :=(l 및 r의 최대값) + 루트 값) 및 루트 값의 최대값
-
max_top :=max_single 및 l + r + 루트 값의 최대값
-
res :=res 및 max_top의 최대값
-
max_single 반환
-
기본 방법에서 다음을 수행하십시오 -
-
루트가 null이면
-
0 반환
-
-
res :=무한대
-
유틸리티(루트)
-
반환 해상도
이해를 돕기 위해 다음 구현을 살펴보겠습니다. −
예시
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
class Solution:
def solve(self, root):
if root is None:
return 0
self.res = float("-inf")
self.utils(root)
return self.res
def utils(self, root):
if root is None:
return 0
l = self.utils(root.left)
r = self.utils(root.right)
max_single = max(max(l, r) + root.val, root.val)
max_top = max(max_single, l + r + root.val)
self.res = max(self.res, max_top)
return max_single
ob = Solution()
root = TreeNode(13)
root.left = TreeNode(12)
root.right = TreeNode(14)
root.right.left = TreeNode(16)
root.right.right = TreeNode(22)
root.right.left.left = TreeNode(4)
root.right.left.right = TreeNode(7)
print(ob.solve(root)) 입력
root = TreeNode(13) root.left = TreeNode(12) root.right = TreeNode(14) root.right.left = TreeNode(16) root.right.right = TreeNode(22) root.right.left.left = TreeNode(4) root.right.left.right = TreeNode(7)
출력
62