Binary-tree-maximum-path-sum
Title Description
Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree. For Example:given the below binary tree,
1
/ \
2 3
Return6.
Ideas
- This problem is the maximum path of the end node in the tree, because we do not know the location of the starting and ending nodes, there must be a root node in a path, so we record the maximum path value corresponding to each node in the tree at each node. Note: This node value is the value of a maximum path that is traversed from that node, except that the node evaluates only one subtree of its child nodes. Based on the calculation of the child nodes and then the root node, we choose to traverse the binary tree. Like what
5
/ \
3 8
/ \ / \
2 4 6 9
/ \ \
1 7 10
Each node corresponds to a value of
32
/ \
7 27
/ \ / \
3 4 13 19
/ \ \
1 7 10
- The value of each node stored here and the last value is not a value, we define a sum variable to store the value we require, and each time we traverse to a node, we need to add the values stored by the left and right child nodes of that node, to see if the path of the node is larger than sum, and replace the sum current value.
- Also note: The value of the node of the tree may be negative, so to determine the return value of the left and right child nodes of each node, if it is smaller than 0, the assignment is 0; Do not assign a value of 0 to the sum, and assign the value to the minimum value 0x80000000 (the maximum value of int is 0x7fffffff)
Code
/**
* Definition forbinary Tree
* Public Classtreenode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode (int x) {val = x;}
* }
*/
Public class Solution {
int sum = 0x80000000; // assign value to minimum value
Public int Maxpathsum (Treenoderoot) {
if (root = null) {
return 0;
}
Getsum (root);
return sum;
}
Public int Getsum (Treenoderoot) {
if (root = null) {
// no nodes, return 0
return 0;
}
// Post-post traversal
int leftnum =getsum (root.left);
int rightnum =getsum (root.right);
// determines whether the value of a child node is less than 0
if (Leftnum < 0) {
Leftnum = 0;
}
if (Rightnum < 0) {
Rightnum = 0;
}
// calculates the current path value, and the existing sum Compare
int temp = leftnum +rightnum + root.val;
if (Temp > Sum) {
sum = temp;
}
// returns one of the larger values in the left and right child nodes
return (Leftnum > Rightnum leftnum:rightnum) + root.val;
}
}
Binary-tree-maximum-path-sum-leetcode