Binary Tree Maximum Path Sum
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:
1) Initialize global variable result to lowest i.e., INTEGER.MIN_VALUE.
2) For each node of the tree, count the max path sum of left subtree(l) and right subtree(r) separately
3) If root is null, return 0.
4) Then find left of root using recursion and if it is non negative store it.
5) Then find right of root using recursion and if it is non negative store it.
6) Add left subtree, right subtree, current node sum and update it to global variable.
7) Now, we need to return to the maximum of the Max Path Sum the left and right subtree and root to parent node
Please let us know your views in comment section.
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
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution
{
int result = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root)
{
findMax(root);
return result;
}
int findMax(TreeNode root)
{
if (root == null) return 0;
int left = Math.max(findMax(root.left), 0);
int right = Math.max(findMax(root.right), 0);
result = Math.max(result, root.val + left + right);
return root.val + Math.max(left, right);
}
}
Try it on Leetcode
1) Initialize global variable result to lowest i.e., INTEGER.MIN_VALUE.
2) For each node of the tree, count the max path sum of left subtree(l) and right subtree(r) separately
3) If root is null, return 0.
4) Then find left of root using recursion and if it is non negative store it.
5) Then find right of root using recursion and if it is non negative store it.
6) Add left subtree, right subtree, current node sum and update it to global variable.
7) Now, we need to return to the maximum of the Max Path Sum the left and right subtree and root to parent node
Please let us know your views in comment section.
Comments
Post a Comment