首页 > 代码库 > [LeetCode]124 Binary Tree Maximum Path Sum
[LeetCode]124 Binary Tree Maximum Path Sum
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
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。