Binary Tree Maximum Path Sum II

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);
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容