File tree Expand file tree Collapse file tree
binary-tree-maximum-path-sum Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ # Definition for a binary tree node.
2+ # class TreeNode:
3+ # def __init__(self, val=0, left=None, right=None):
4+ # self.val = val
5+ # self.left = left
6+ # self.right = right
7+ from collections import deque
8+ class Solution :
9+ def maxPathSum (self , root : Optional [TreeNode ]) -> int :
10+
11+ # # Initially thought I need to use BFS ( misunderstood the question)
12+ # if not root:
13+ # return
14+ # queue = deque([root])
15+ # result = []
16+ # val = 0
17+ # max_sum = float('-inf')
18+ # while queue:
19+ # currentNode = queue.popleft()
20+ # result.append(currentNode.val)
21+ # val += currentNode.val
22+
23+ # if currentNode.left:
24+ # queue.append(currentNode.left)
25+ # val += currentNode.left.val
26+ # if currentNode.right:
27+ # queue.append(currentNode.right)
28+ # val += currentNode.right.val
29+ # max_sum = max(val, max_sum)
30+ # val = 0
31+ # return max_sum
32+ res = [root .val ]
33+
34+ def dfs (root ):
35+ if not root :
36+ return 0
37+ leftMax = dfs (root .left )
38+ rightMax = dfs (root .right )
39+ leftMax = max (leftMax , 0 )
40+ rightMax = max (rightMax , 0 )
41+
42+ res [0 ] = max (res [0 ], root .val + leftMax + rightMax )
43+
44+ return root .val + max (leftMax , rightMax )
45+ dfs (root )
46+ return res [0 ]
You can’t perform that action at this time.
0 commit comments