二叉树最大路径和

来源:互联网 发布:xtream path 1.6 mac 编辑:程序博客网 时间:2024/05/22 08:39

问题

给出一个二叉树,找到其中的最大路径和。

路径可以从树中任意一个节点开始和结束。

例如:

给出如下二叉树,

       1

      / \

    2    3

返回6

java实现:

public static int maxPathSum(TreeNode root){if(root==null){return 0;}int value=root.val;int leftMax=0;int rightMax=0;if(root.left!=null){leftMax=maxPathSum(root.left);if(leftMax>0){value+=leftMax;}}if(root.right!=null){rightMax=maxPathSum(root.right);if(rightMax>0){value+=rightMax;}}        //更新最大值  max is the max of {(root.val),(root.val+leftMax),(root.val+rightMax),(root.val+leftMax+rightMax)}if(value>max){max=value;}//返回值        //return max of (root.val, root.val+leftMax,root.val+rightMax)return Math.max(root.val,Math.max(leftMax, rightMax)+root.val);}public static int maxPath(TreeNode root){if(root==null){return 0;}maxPathSum(root);return max;}


0 0