Binary Tree Maximum Path Sum

本文详细介绍了如何通过递归搜索来找出二叉树中任意两个节点之间的路径,使得该路径上的节点值之和达到最大。通过深入分析节点之间的连接关系,我们能够高效地找到最优路径,并提供了具体的代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

题目分析:求二叉树中任意两个节点的路径的最大值。想到的是如果求经过某个节点的向下的某个节点的最大值则是F(left)+val+F(right),这时候可以更新最大值,所以可以递归求解,但是如果要求经过这个节点的某条路径,则要么是左子树+当前点,要么是右子树加当前点,或者当前点,因为分支路径要么经过左子树要么经过右子树。

具体代码如下:

private int maxSum=Integer.MIN_VALUE;  //用于记录全局搜索的最大值
	  public int maxPathSum(TreeNode root) {
		  maxSum=Integer.MIN_VALUE;
		  if(root==null) return 0;
		  scanMax(root);
		  return maxSum;
	    }
	  /**
	   * 通过递归的搜索左右子树,然后计算,包括当前值和左右子树的最大值,更新最大值
	   * @param 根节点
	   * @return 包括root在内的左分支,右分支和没有分支的最大值
	   * */
	  public int scanMax(TreeNode root)
	  {
		  if(root==null)  return 0;
		  int left=scanMax(root.left);
		  int right=scanMax(root.right);
		  int val=root.val;
		  if(left>0) val+=left;
		  if(right>0) val+=right;
		  if(val>maxSum) maxSum=val;
		  return Math.max(root.val, Math.max(root.val+left, root.val+right));
		  
	  }



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值