[LeetCode][C++] #124. Binary Tree Maximum Path Sum

Newone Tsai
2 min readMay 1, 2021

--

[Hard][Question]:

A path in a binary tree is a sequence of nodes where each pair of adjacent nodes in the sequence has an edge connecting them. A node can only appear in the sequence at most once. Note that the path does not need to pass through the root.

The path sum of a path is the sum of the node’s values in the path.

Given the root of a binary tree, return the maximum path sum of any path.

Example 1:

Input: root = [1,2,3]
Output: 6
Explanation: The optimal path is 2 -> 1 -> 3 with a path sum of 2 + 1 + 3 = 6.

Example 2:

Input: root = [-10,9,20,null,null,15,7]
Output: 42
Explanation: The optimal path is 15 -> 20 -> 7 with a path sum of 15 + 20 + 7 = 42.

Constraints:

  • The number of nodes in the tree is in the range [1, 3 * 104].
  • -1000 <= Node.val <= 1000

My Solution[C++]:

[Ideas]: 利用遞迴找出最大值,主要分兩種可能。

1. 此node為轉折點,也就是說從left -> node -> right

2. 此node為經過點,也就是此node+Left/right 為最大值,與node的祖父節點一起累加上去

遞迴的方式是:

Step1. 找出左邊節點往下的最大值,並且與零取max = Left_max

Step2. 找出右邊節點往下的為大值,並且與零取max = Right_max

Step3. 此節點當轉折點,所以其值為value+Left_max+Right_max

Step4. 與之前的max_answer再取一次max

Step5. 若當經過點,回傳value+ Left_max or Right_max

--

--

Newone Tsai
Newone Tsai

Written by Newone Tsai

I took the one less traveled by, and that has made all the difference.

No responses yet