I'm trying to store and print the actual path in the problem of finding maximum path sum in a binary tree. I already know how to find the maximum path sum (below), but how can we add a snippet to output the actual path?
private int maxSum;
public int maxPathSum(TreeNode root) {
maxSum = Integer.MIN_VALUE;
findMax(root);
return maxSum;
}
private int findMax(TreeNode p) {
if (p == null) return 0;
int left = findMax(p.left);
int right = findMax(p.right);
maxSum = Math.max(p.val + left + right, maxSum);
int ret = p.val + Math.max(left, right);
return ret > 0 ? ret : 0;
}
May you can try this.