Skip to content

Commit 36822a0

Browse files
Merge pull request #109 from divya1509/master
Create Binary Tree Maximum Path Sum
2 parents ba7900a + 4998c64 commit 36822a0

1 file changed

Lines changed: 46 additions & 0 deletions

File tree

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
// link- https://leetcode.com/problems/binary-tree-maximum-path-sum/
2+
3+
// Approach:
4+
// Since a binary tree can have max 2 children so the path with max sum can either include both the children or one
5+
// depending upon the max value that can be generated.
6+
// The same logic has been implemented in the following code which stores the final answer in the variable max
7+
8+
9+
/**
10+
* Definition for a binary tree node.
11+
* public class TreeNode {
12+
* int val;
13+
* TreeNode left;
14+
* TreeNode right;
15+
* TreeNode() {}
16+
* TreeNode(int val) { this.val = val; }
17+
* TreeNode(int val, TreeNode left, TreeNode right) {
18+
* this.val = val;
19+
* this.left = left;
20+
* this.right = right;
21+
* }
22+
* }
23+
*/
24+
class Solution {
25+
int max = -1001;
26+
27+
private int solve(TreeNode root) {
28+
if(root == null) return 0;
29+
30+
int ans_left = 0, ans_right = 0;
31+
if(root.left != null) ans_left = Math.max(solve(root.left), 0);
32+
if(root.right != null) ans_right = Math.max(solve(root.right), 0);
33+
34+
int temp = root.val + Math.max(ans_left, ans_right);
35+
max = Math.max(temp, max);
36+
max = Math.max(root.val + ans_left + ans_right, max);
37+
return temp;
38+
39+
}
40+
41+
public int maxPathSum(TreeNode root) {
42+
max = -1001;
43+
solve(root);
44+
return max;
45+
}
46+
}

0 commit comments

Comments
 (0)