[刷题]Binary Tree Maximum Path Sum

来源:互联网 发布:linux 数值运算 编辑:程序博客网 时间:2024/06/07 03:44

[LintCode]Binary Tree Maximum Path Sum

/** * Definition of TreeNode: * public class TreeNode { *     public int val; *     public TreeNode left, right; *     public TreeNode(int val) { *         this.val = val; *         this.left = this.right = null; *     } * } */public class Solution {    /**     * @param root: The root of binary tree.     * @return: An integer.     */        private class RstType {        int maxPath;        int singlePath;        public RstType(int s, int m) {            singlePath = s;            maxPath = m;        }    }        private RstType helper(TreeNode root) {        if (root == null) {            return new RstType(0, Integer.MIN_VALUE);        }                // divide        RstType left = helper(root.left);        RstType right = helper(root.right);                // conquer        int singlePath = Math.max(0,            root.val + Math.max(left.singlePath, right.singlePath));        int maxPath = Math.max(Math.max(left.maxPath, right.maxPath),            root.val + left.singlePath + right.singlePath);        return new RstType(singlePath, maxPath);    }        public int maxPathSum(TreeNode root) {        // 2015-3-23        RstType rst = helper(root);        return rst.maxPath;    }}


0 0
原创粉丝点击