【小熊刷题】Binary Tree Maximum Path Sum

来源:互联网 发布:mac python如何加载库 编辑:程序博客网 时间:2024/04/29 23:55

Question

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

For example, given the below binary tree,

1

/ \

2 4

/ \2 3

The highlighted path yields the maximum sum 10.

https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/

*Difficulty: Hard, Frequency: Medium

Solution

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private int maxSum;    public int maxPathSum(TreeNode root) {        maxSum = Integer.MIN_VALUE;        findMax(root);        return maxSum;    }    public int findMax(TreeNode node){        if(node == null) return 0;        int left = findMax(node.left);        int right = findMax(node.right);        maxSum = Math.max(node.val+left+right, maxSum);        int ret = Math.max(right, left) + node.val;        return ret > 0 ? ret : 0;    }}
0 0