#94 Binary Tree Maximum Path Sum

本文探讨了在二叉树中寻找最大路径和的问题。路径可以从任意节点开始和结束,并可能穿越根节点。通过递归算法,我们实现了高效求解这一问题的方法。

题目描述:

Given a binary tree, find the maximum path sum.

The path may start and end at any node in the tree.

Example

Given the below binary tree:

  1
 / \
2   3

return 6.

题目思路:

这题因为path可以起始/终止于任何一个node,似乎不太好下手。但是可以发现,无论怎样,path都会经过某些node。那如果对于某一node,它的左子树(包含左节点)出一条path(这条path必须不能同时包含左子树的左右子树),右子树(包含右节点)出一条path,那么max可能是左path,或者右path,或者只是这个node本身,或者是左path+node+右path。

Mycode(AC = 51ms):

/**
 * Definition of TreeNode:
 * class TreeNode {
 * public:
 *     int val;
 *     TreeNode *left, *right;
 *     TreeNode(int val) {
 *         this->val = val;
 *         this->left = this->right = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param root: The root of binary tree.
     * @return: An integer
     */
    int maxPathSum(TreeNode *root) {
        // write your code here
        if (root == NULL) {
            return 0;
        }
        
        int max_sum = INT_MIN;
        maxPathSum(root, max_sum);
        return max_sum;
    }
    
    int maxPathSum(TreeNode *root, int& max_sum) {
        if (!root->left && !root->right) {
            max_sum = max(max_sum, root->val);
            return root->val;
        }
        
        int left = INT_MIN, right = INT_MIN, result = INT_MIN;
        
        // get the max path from left subtree (include left node)
        if (root->left) {
            left = maxPathSum(root->left, max_sum);
            result = max(root->val, root->val + left);
        }
        
        // get the max path from right subtree (include right node)
        if (root->right) {
            right = maxPathSum(root->right, max_sum);
            result = max(result, max(root->val, root->val + right));
        }
        
        if (left != INT_MIN && right != INT_MIN) {
            max_sum = max(left + right + root->val, max(max_sum, result));
        }
        else {
            max_sum = max(max_sum, result);
        }
        
        return result;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值