[leetcode]Binary Tree Maximum Path Sum

来源:互联网 发布:锐捷mac客户端最新 编辑:程序博客网 时间:2024/06/07 05:27

from : https://leetcode.com/submissions/detail/36066022/

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   3

Return 6.

/** * 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 max = 0;public int maxPathSum(TreeNode root) {if (null != root) {max = root.val;}sums(root);return max;}private int sums(TreeNode root) {if (null == root) {return 0;}int lsum = sums(root.left);int rsum = sums(root.right);int sum = root.val;if (lsum > 0) {sum += lsum;}if (rsum > 0) {sum += rsum;}if (sum > max) {max = sum;}// as a child, return (root.val+left) or (root.val+right)int off = 0;if (lsum > 0 && rsum > 0) {off = lsum < rsum ? lsum : rsum;}return sum - off;}}


0 0