124. 二叉树中的最大路径和-H

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/scylhy/article/details/87931061

124. 二叉树中的最大路径和

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]

   1
  / \
 2   3

输出: 6
示例 2:

输入: [-10,9,20,null,null,15,7]

-10
/ \
9  20
  /  \
 15   7

输出: 42

  • 分析
    计算树的通路上的最大和;一直有个担心,怕计算的路径和是局部的;
    这道题,对于节点N,很明显有三个通路,通过递归bottom-top方式,首先比较其左右子树+N的最大路径,即L+N,R+N,L+R+N,比较最大路径,计算结束;上传给父节点,要注意,*+N<0,则对父节点是无用的,因为求最大,加个负数是没用的,并且因为bottom-top,更细的子树已经计算完全,无需担心求得的路径是局部的问题,所以当 *+N是负数时,返回0,表示该路径上经过N,的最大路径和0。
    所谓担心局部问题,是在不管是否经过N,用返回值表示当前子树上的最大路径,并且可能重复计算上N。
  • code
package main
import (
	"fmt"
	"math"
)
type TreeNode struct {
  Val int
  Left *TreeNode
  Right *TreeNode
}
var max int
func maxPathSum(root *TreeNode) int {
	max=math.MinInt64
	findMaxPath(root)
	return max
}
func findMaxPath(root *TreeNode) int {
	if root==nil{
		return 0
	}
	a,b,c:=0,0,0
	a=findMaxPath(root.Left)
	b=findMaxPath(root.Right)
	c=a+b+root.Val
	if c>max{max=c}
	a=a+root.Val;b=b+root.Val
	if a<b{a=b}
	if a<0{a=0}
	//返回0,是这个方法的精髓
	//即代表,其父节点不使用其路径上的最大和
	//因为子树上的最大路径和为负数,谁加他,谁少
	return a
}
func main(){

	var t1,t2,t3,t4,t5 TreeNode
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1
	t1.Val=1;t2.Val=2;t3.Val=3
	t1.Left=&t2;t1.Right=&t3
	fmt.Println(maxPathSum(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1
	t1.Val=-10;t2.Val=9;t3.Val=20;t4.Val=15;t5.Val=7
	t1.Left=&t2;t1.Right=&t3;t3.Left=&t4;t3.Right=&t5
	fmt.Println(maxPathSum(&t1))
	t1=TreeNode{};t2=t1;t3=t1;t4=t1;t5=t1
	t1.Val=-2;t2.Val=-1
	t1.Left=&t2
	fmt.Println(maxPathSum(&t1))
}

猜你喜欢

转载自blog.csdn.net/scylhy/article/details/87931061