You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When a root node of binary tree is given, find max-sum of sequence of nodes.
Sequence of nodes means that traverse node to node, but not visit same node.
example
/*
-100
/ \
2 3
/ \
4 7
*/
Node(7) -> Node(3) is the sequence that has sum of 10.
/*
1
/ \
2 3
/ \ / \
4 5 6 7
*/
Node(7) -> Node(3) -> Node(1) -> Node(2) -> Node(5) is the sequence that has sum of 18.
Naive Approach
We can get a single maximum sum path, that start from parent to child.
We can also divide this problem to [LEFT-SIDE] + head + [RIGHT-SIDE].
Then, repeat this at every node.
The algorithm above has a time complexity of O(n^2), because it visits same node many times.
We can reduce time complexity to O(n) by combining travel and pathSum into one.
The node has two values, one is max path part(the connection part), it will be used as a child node.
The other one is complete part, where the node is the head of the connection.
The code is below.
constmaxPathSum=function(root){letmaxSum=Number.NEGATIVE_INFINITY;functionpathSum(node){if(node===null)return0;constval=node.val;letleft=pathSum(node.left);letright=pathSum(node.right);left=Math.max(left,0);right=Math.max(right,0);// It is the complete part.maxSum=Math.max((val+left+right),maxSum);// It is the connection part.returnval+Math.max(left,right);}pathSum(root);returnmaxSum;};
The text was updated successfully, but these errors were encountered:
Problem
When a root node of binary tree is given, find max-sum of sequence of nodes.
Sequence of nodes means that traverse node to node, but not visit same node.
Naive Approach
We can get a single maximum sum path, that start from parent to child.
We can also divide this problem to [LEFT-SIDE] + head + [RIGHT-SIDE].
Then, repeat this at every node.
The code is below.
Better Way
The algorithm above has a time complexity of O(n^2), because it visits same node many times.
We can reduce time complexity to O(n) by combining travel and pathSum into one.
The node has two values, one is max path part(the connection part), it will be used as a child node.
The other one is complete part, where the node is the head of the connection.
The code is below.
The text was updated successfully, but these errors were encountered: