leetCode练习(124)

来源:互联网 发布:linux用户和组管理 编辑:程序博客网 时间:2024/04/28 01:15

题目:Binary Tree Maximum Path Sum

难度:hard

问题描述:

Given a binary tree, find the maximum path sum.

For this problem, a path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. The path does not need to go through the root.

For example:
Given the below binary tree,

       1      / \     2   3

Return 6.

解题思路:

通过递归,求解每个经过最高层节点n的最大值。经过‘1’节点的最大值=1+1.left的单边最大值+1.right的单边最大值。也就是说,对于节点n,其返回值为n.val加上其中一条边或者0条边的值。同时设置全局变量保存每各经过的最高层节点路径和中的最大者。

代码如下:

/** * Definition for a binary tree node. * public class TreeNode { *     int val; *     TreeNode left; *     TreeNode right; *     TreeNode(int x) { val = x; } * } */public class Solution {    private int res=Integer.MIN_VALUE;    public int maxPathSum(TreeNode root) {        maxsum(root);return res;    }    private int maxsum(TreeNode root){if(root==null) return Integer.MIN_VALUE;int left=maxsum(root.left);int right=maxsum(root.right);if(root.val>=0){if(left>0){if(right>0){res=Math.max(res, root.val+left+right);}else{res=Math.max(res, root.val+left);}}else{if(right>0){res=Math.max(res, root.val+right);}else{res=Math.max(res, root.val);}}}else{//root<0if(left>0){if(right>0){res=Math.max(res,root.val+left+right);}else{res=Math.max(res, left);}}else{if(right>0){res=Math.max(res, root.val+right);}else{res=Math.max(res,root.val);}}}return Math.max(root.val+Math.max(0, left), root.val+Math.max(0, right));}}

0 0
原创粉丝点击