LeetCode 124. 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 must contain at least one node and does not need to go through the root.

For example:
Given the below binary tree,

   1
  / \
 2   3

Return 6.

求二叉树任意起止点构成的路径的值最大和

虽然是任意起止点,但此路径一定会有根节点,因此对于该根节点:
max = root.val+maxPathSum(左子树)(>0才加)+maxPathSum(右子树)(>0才加);

但对于每次递归的返回,则应该是
return max(root.val,root.val+maxPathSum(左子树),root.val+maxPathSum(右子树));

 public static int max;

            public static int maxPathSum(TreeNode root) {
                if(root==null)
                    return 0;
                max = Integer.MIN_VALUE;
                maxPathSum2(root);
                return max;
            }
            public static int maxPathSum2(TreeNode root) {
                if(root==null)
                    return 0;
                int temp1 = maxPathSum2(root.left);
                int temp2 = maxPathSum2(root.right);
                int temp = root.val;
                if(temp1>0)temp+=temp1;
                if(temp2>0)temp += temp2;
                max = temp>max?temp:max;
                return max(root.val,root.val+temp1,root.val+temp2);

            }
            public static int max(int i,int j,int k){
                return i > (j>k?j:k) ? i : (j>k?j:k);
            }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值