Binary Tree Maximum Path Sum

来源:互联网 发布:linux help分段显示 编辑:程序博客网 时间:2024/04/30 09:08

题目原型:

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.

基本思路:

递归回溯,从总体上来讲,最大路径和是,根节点的值、根节点的值加上左子树最大路径和、根节点的值加上右子树最大路径和,这三者中的最大值。

int max = Integer.MIN_VALUE;public int maxPathSum(TreeNode root){if(root==null)return 0;getMaxPathSum(root);return max;}public int getMaxPathSum(TreeNode root){if(root==null)return 0;int lmax = 0;int rmax = 0;int sum = 0;if(root.left!=null){lmax = getMaxPathSum(root.left);}if(root.right!=null){rmax = getMaxPathSum(root.right);}if(lmax>0)sum+=lmax;if(rmax>0)sum+=rmax;sum+=root.val;//注意最大值是个全局变量,不随递归返回max = max>sum?max:sum;//返回根节点的值、根节点的值加上左子树最大路径和、根节点的值加上右子树最大路径和。三者中最大的值return Math.max(root.val, Math.max(root.val+lmax, root.val+rmax));}



0 0
原创粉丝点击