forked from BigEggStudy/LeetCode-CS
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path0124-BinaryTreeMaximumPathSum.cs
More file actions
33 lines (26 loc) · 912 Bytes
/
0124-BinaryTreeMaximumPathSum.cs
File metadata and controls
33 lines (26 loc) · 912 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//-----------------------------------------------------------------------------
// Runtime: 104ms
// Memory Usage: 28.4 MB
// Link: https://leetcode.com/submissions/detail/257942576/
//-----------------------------------------------------------------------------
using System;
namespace LeetCode
{
public class _0124_BinaryTreeMaximumPathSum
{
private int max_sum = int.MinValue;
public int MaxPathSum(TreeNode root)
{
MaxPathSumCore(root);
return max_sum;
}
public int MaxPathSumCore(TreeNode root)
{
if (root == null) return 0;
var leftSum = Math.Max(MaxPathSumCore(root.left), 0);
var rightSum = Math.Max(MaxPathSumCore(root.right), 0);
max_sum = Math.Max(max_sum, root.val + leftSum + rightSum);
return root.val + Math.Max(leftSum, rightSum);
}
}
}