Given a binary tree, find the maximum path sum from root.
The path may end at any node in the tree and contain at least one node in it.
Example
Given the below binary tree:
1
/ \
2 3
return 4. (1->3)
这道题比较简单,因为题目提示了是求从根节点出发的最大路径和,只需要记录一条当前path, 随时更新一个maxSum, 用递归和回溯就可以解决了。
public class Solution {
/*
* @param root: the root of binary tree.
* @return: An integer
*/
int maxSum = Integer.MIN_VALUE;
public int maxPathSum2(TreeNode root) {
// write your code here
if (root == null){
return Integer.MIN_VALUE;
}
ArrayList<Integer> path = new ArrayList<>();
helper(root, path, 0);
return maxSum;
}
//递归的定义:当前路径path,当前根节点root, 找到其path sum, 如果比maxSum大,
//更新maxSum
private void helper(TreeNode root, ArrayList<Integer> path, int curtSum){
if (root == null){
return;
}
path.add(root.val);
curtSum += root.val;
if (curtSum > maxSum){
maxSum = curtSum;
}
helper(root.left, path, curtSum);
helper(root.right, path, curtSum);
path.remove(path.size() - 1);
}
}