Description:
Given a 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 does not need to go through the root.
Solution:
Classic tree problem.
There are three types of longest paths for each node: the longest path from its left child node(parent node included or not included), right child node(parent node included or not included), and both path from left child node and right child node(parent node must be included).
<span style="font-size:18px;">import java.util.*;
public class Solution {
ArrayList<Integer> list = new ArrayList<Integer>();
public int maxPathSum(TreeNode root) {
findFarestNode(root);
int max = Integer.MIN_VALUE;
for (Iterator<Integer> ite = list.iterator(); ite.hasNext();) {
int cur = ite.next();
max = Math.max(max, cur);
}
return max;
}
public int findFarestNode(TreeNode root) {
if (root == null)
return 0;
int left = findFarestNode(root.left);
left = Math.max(left, 0);
int right = findFarestNode(root.right);
right = Math.max(right, 0);
int current = root.val + left + right;
list.add(current);
int ret = Math.max(left, right) + root.val;
ret = Math.max(ret, 0);
return ret;
}
}</span>