我正在尝试存储和打印在二叉树中查找最大路径总和的问题中的实际路径。我已经知道如何找到最大路径总和(下面),但是我们如何添加一个片段来输出实际路径呢?
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;
}