Skip to content

Commit 12ace2a

Browse files
committed
Add Solution for 124 in cpp and go
1 parent dfb664d commit 12ace2a

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
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+
};
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
}

0 commit comments

Comments
 (0)