背景
題目英文
Given a non-empty binary tree, find the maximum path sum.
For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path must contain at least one node and does not need to go through the root.
Example 1:
Input: [1,2,3]
1
/ \
2 3
Output: 6
Example 2:
Input: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
Output: 42
題目中文
給定一個非空二叉樹,返回其最大路徑和。
本題中,路徑被定義爲一條從樹中任意節點出發,達到任意節點的序列。該路徑至少包含一個節點,且不一定經過根節點。
示例 1:
輸入: [1,2,3]
1
/ \
2 3
輸出: 6
示例 2:
輸入: [-10,9,20,null,null,15,7]
-10
/ \
9 20
/ \
15 7
輸出: 42
算法實現
8
/ \
-3 7
/ \
1 4
考慮左子樹 -3 的路徑的時候,我們有左子樹 1 和右子樹 4 的選擇,但我們不能同時選擇。
如果同時選了,路徑就是 … -> 1 -> -3 -> 4 就無法通過根節點 8 了。
所以我們只能去求左子樹能返回的最大值,右子樹能返回的最大值,選一個較大的。
/**
* Definition for a binary tree node.
* public class TreeNode {
* public int val;
* public TreeNode left;
* public TreeNode right;
* public TreeNode(int x) { val = x; }
* }
*/
public class Solution
{
private int _max = int.MinValue;
public int MaxPathSum(TreeNode root)
{
MaxPath(root);
return _max;
}
private int MaxPath(TreeNode current)
{
if (current == null)
return 0;
int left = Math.Max(MaxPath(current.left), 0);
int right = Math.Max(MaxPath(current.right), 0);
_max = Math.Max(_max, current.val + left + right);
return current.val + Math.Max(left, right);
}
}
實驗結果
- 狀態:通過
- 93 / 93 個通過測試用例
- 執行用時: 152 ms, 在所有 C# 提交中擊敗了 86.96% 的用戶
- 內存消耗: 29.7 MB, 在所有 C# 提交中擊敗了 37.50% 的用戶
相關圖文
1. “數組”類算法
- LeetCode實戰:三數之和
- LeetCode實戰:最接近的三數之和
- LeetCode實戰:求衆數
- LeetCode實戰:缺失的第一個正數
- LeetCode實戰:快樂數
- LeetCode實戰:尋找兩個有序數組的中位數
- LeetCode實戰:盛最多水的容器
- LeetCode實戰:刪除排序數組中的重複項
- LeetCode實戰:搜索旋轉排序數組
- LeetCode實戰:螺旋矩陣
- LeetCode實戰:螺旋矩陣 II
2. “鏈表”類算法
- LeetCode實戰:兩數相加
- LeetCode實戰:刪除鏈表的倒數第N個節點
- LeetCode實戰:合併兩個有序鏈表
- LeetCode實戰:合併K個排序鏈表
- LeetCode實戰:兩兩交換鏈表中的節點
- LeetCode實戰:旋轉鏈表
- LeetCode實戰:環形鏈表
3. “棧”類算法
4. “隊列”類算法
5. “遞歸”類算法
6. “字符串”類算法
7. “樹”類算法
8. “哈希”類算法
9. “搜索”類算法
10. “動態規劃”類算法
11. “回溯”類算法
12. “數值分析”類算法