TODO: 124. Binary Tree Maximum Path Sum

#dfs #tree

Problem

Intuition

Original Tree

In the above tree, with node 3

maxLeft = 4

maxRight = 5

Before we can pick a node to make a path, we should pick the node which maximises the path value

maxLeftRight=max(maxLeft,maxRight)maxLeftRight = max(maxLeft, maxRight)

max(3+4(node 4), 3+5(node 5) = node(5)

So 5 is picked and added to node 3, so the value of 5 is pushed upwards to node 3

maxRootLeftRight=max(root.val,root.val+maxLeftRight)maxRootLeftRight = max(root.val, root.val+maxLeftRight)

Here in this binary tree we should check if the full binary tree val is larger than root value

maxAll=max(maxRootLeftRight,root.val)maxAll = max(maxRootLeftRight, root.val)

In the above case, since all are positive ints it will pick maxValue as maxRootLeftRight

maxRootLeftRight is max value
root.val is max

Time Complexity

Space Complexity

Solution

Last updated