https://leetcode.com/problems/binary-tree-maximum-path-sum/
找到二叉树中路径的最大和,路径起点终点均为任意节点
前序遍历,返回以当前root为路径起点的sum最大值,全局变量max在前序遍历里面更新,将root视为路径中间一点,路径起点位于左子树中,终点位于右子树中
public class Solution {
int max = Integer.MIN_VALUE;
public int maxPathSum(TreeNode root) {
preOrder(root);
return max;
}
private int preOrder(TreeNode root) {
if (root == null) {
return 0;
}
int left = Math.max(0, preOrder(root.left));
int right = Math.max(0, preOrder(root.right));
max = Math.max(max, left + right + root.val);
return Math.max(left, right) + root.val;
}
}