【两次过】Lintcode 94. 二叉树中的最大路径和

本文探讨了在任意节点开始和结束的二叉树路径中寻找最大路径和的问题,通过分治法解决,考虑四种情况并使用递归辅助函数进行求解。

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

给出一棵二叉树,寻找一条路径使其路径和最大,路径可以在任一节点中开始和结束(路径和为两个节点之间所在路径上的节点权值之和)

样例

给出一棵二叉树:

       1
      / \
     2   3 

返回 6


解题思路:

利用分治法 解决问题
需要一个变量不断记录带有root点的路径的最大值 curr_max 局部变量
需要另一个变量记录当前的最大路径值 max 类变量
最后返回 当前的最大路径值

思路:
有4种情况要考虑
left + root
right + root
root
left + right + root

不断往上传递的值 只可能是 1, 2, 3中的一种
第四种情况只可能保存在 max里面 而不可能在 curr_max,因为第四种情况可能出现^这种的分支结构,如果向上传递就不能构成一条路径。

/**
 * Definition of TreeNode:
 * public class TreeNode {
 *     public int val;
 *     public TreeNode left, right;
 *     public TreeNode(int val) {
 *         this.val = val;
 *         this.left = this.right = null;
 *     }
 * }
 */

public class Solution {
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    private int max = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        // write your code here
        helper(root);
        
        return max;
    }
    
    private int helper(TreeNode root){
        if(root == null)
            return 0;
        
        //Divide
        int left = helper(root.left);
        int right = helper(root.right);
        
        //Conquer
        int curMax = Math.max(root.val, Math.max(left+root.val, right+root.val)); //root -> any
        max = Math.max(max, Math.max(curMax,left+root.val+right));  //any -> any
        
        return curMax;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值