标签:leetcode
https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/
http://blog.csdn.net/linhuanmars/article/details/22969069
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public int maxPathSum(TreeNode root) { if (root == null) return 0; Result result = new Result(); result.value = Integer.MIN_VALUE; visit(root, result); return result.value; } Values visit(TreeNode node, Result result) { int full = 0; int sub = 0; if (node.left == null && node.right == null) { sub = node.val; full = sub; } else if (node.left != null && node.right == null) { Values leftvalues = visit(node.left, result); sub = max(node.val, node.val + leftvalues.sub); full = sub; } else if (node.left == null && node.right != null) { Values rightvalues = visit(node.right, result); sub = max(node.val, node.val + rightvalues.sub); full = sub; } else { // If curren node has both left and right // // the maxpath passing this node would be // max( node.val, this node only // node.val + left.sub this node with left sub tree // node.val + right.sub this node with right sub tree // node.val + left.sub + right.sub this path from its left subtree to right subtree // // However, // the maxpath when current node is subtree // it cannot be // (node.val + left.sub + right.sub) Values leftvalues = visit(node.left, result); Values rightvalues = visit(node.right, result); sub = max(node.val, node.val + leftvalues.sub, node.val + rightvalues.sub); full = max(sub, node.val + leftvalues.sub + rightvalues.sub); } result.value = max(result.value, full); return new Values(full, sub); } private int max(int...ints) { int r = Integer.MIN_VALUE; for (int i : ints) r = Math.max(r, i); return r; } private static class Values { // MathPath when passing this node. private int full; // MathPath when using this node as a sub tree. // NOTE // It is different from full that // current node must be endpoint. private int sub; Values(int full, int sub) { this.full = full; this.sub = sub; } } private static class Result { private int value; } }
[LeetCode]124 Binary Tree Maximum Path Sum
标签:leetcode
原文地址:http://7371901.blog.51cto.com/7361901/1600192