File tree Expand file tree Collapse file tree 2 files changed +64
-0
lines changed
solution/0124.Binary Tree Maximum Path Sum Expand file tree Collapse file tree 2 files changed +64
-0
lines changed Original file line number Diff line number Diff line change
1
+ /* *
2
+ * Definition for a binary tree node.
3
+ * struct TreeNode {
4
+ * int val;
5
+ * TreeNode *left;
6
+ * TreeNode *right;
7
+ * TreeNode(int x) : val(x), left(NULL), right(NULL) {}
8
+ * };
9
+ */
10
+ class Solution {
11
+ public:
12
+ int maxPathSum (TreeNode* root) {
13
+ int maxInt = INT_MIN;
14
+ dfs (root,maxInt);
15
+ return maxInt;
16
+ }
17
+
18
+
19
+ int dfs (TreeNode *root,int &maxInt){
20
+ if (root == nullptr )return 0 ;
21
+
22
+ int left = max (dfs (root->left ,maxInt),0 );
23
+ int right = max (dfs (root->right ,maxInt),0 );
24
+ maxInt = max (maxInt,left + right + root->val );
25
+ return max (left,right) + root->val ;
26
+ }
27
+ };
Original file line number Diff line number Diff line change
1
+ /**
2
+ * Definition for a binary tree node.
3
+ * type TreeNode struct {
4
+ * Val int
5
+ * Left *TreeNode
6
+ * Right *TreeNode
7
+ * }
8
+ */
9
+
10
+ import (
11
+ "math"
12
+ )
13
+
14
+ func maxPathSum (root * TreeNode ) int {
15
+ maxInt := math .MinInt32
16
+ dfs (root ,& maxInt )
17
+ return maxInt
18
+ }
19
+
20
+ func dfs (root * TreeNode ,maxInt * int ) int {
21
+ if root == nil {
22
+ return 0
23
+ }
24
+
25
+ left := max (0 ,dfs (root .Left ,maxInt ))
26
+ right := max (0 ,dfs (root .Right ,maxInt ))
27
+ * maxInt = max (* maxInt ,root .Val + left + right )
28
+ return max (left ,right ) + root .Val
29
+ }
30
+
31
+
32
+ func max (a ,b int ) int {
33
+ if a > b {
34
+ return a
35
+ }
36
+ return b
37
+ }
You can’t perform that action at this time.
0 commit comments