Leetcode Binary Tree Maximum Path Sum

Problem

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.

Solution

public class Solution {
   int ans;
   public int maxPathSum(TreeNode root) {
		ans=root.val;
		search(root);
		return ans;
	}
	public int search(TreeNode root){
	    int res=root.val;
	    int left=0,right=0;
		if(root.left!=null){
		    left=search(root.left);
		    if(left>ans)ans=left;
		    if(left>0){
		        res+=left;
		    }
		}
		if(root.right!=null){
		    right=search(root.right);
		    if(right>ans)ans=right;
		    if(right>0){
		        res+=right;
		    }
		}
		if(res>ans)ans=res;
		int sum=root.val;
		int maxVal=Math.max(left, right);
		if(maxVal>0)sum+=maxVal;
		return sum;
	}
	public static void main(String[] args) {
		Solution sln = new Solution();
	}
}

思路

search函数返回以root以根的树上面从root出发的Maximum Path Sum,也就是说这个Path要么在root的左子树,要么在右子树,不会跨过左右子树。

开始时在search函数中返回了以root为根的树上的Maximum Path Sum,允许Path同时在左右子树上,这种做法在求当前树的Maximum Path Sum时是对的,但是返回到上一层的值是没意义的,因为当上一层的节点连接到当前的root节点时已经不是题目要求的Path了。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值