[LeetCode 124] Binary Tree Maximum Path Sum (DFS/二叉树)

124. Binary Tree Maximum Path Sum

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.


题解:
有关二叉树的题目,最常见的思路就是递归。

题目要求得是对路径上各结点求和的最大值,用递归的思路来想,各自求两个子树的路径求和的最大值,然后与自己的值相加,得到结果。但就像题目中所说的,答案的路径不一定是经过root的,这种做法没有考虑答案路径只在其中一边的子树的情况。

那么可以考虑转换递归函数求的东西,比如换成求以当前root为端点的路径的sum的最大值。如果这样求,就可以在递归的途中,可以通过左子树的最大值和右子树的最大值和自身结点的值,得到一个经过当前结点的最大的sum,将其记录,递归完成后可找到总体的最大的sum。

因为每个结点只访问1次,所以总复杂度为O(n)



代码:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

#include <algorithm>
#define INF 0x80000000
class Solution {
public:
    int maxPathSum(TreeNode* root) {
        maxSum = INF;      //现将本来的值置为最小
        int sum = dfs(root);  //递归处理
        if (sum > maxSum) maxSum = sum;   //排除特殊样例 (root==NULL)
        return maxSum;
    }

    static int dfs(TreeNode* root) {
        if (root == NULL) return 0;   //边界条件

        int left_sum = dfs(root->left);
        int right_sum = dfs(root->right);

        if (left_sum < 0) left_sum = 0;   //如果子树求得的值为负,便忽略
        if (right_sum < 0) right_sum = 0;

        if (maxSum < left_sum + right_sum + root->val)
            maxSum = left_sum + right_sum + root->val;
        return max(left_sum, right_sum) + root->val;
    }
private:
    //声明一个静态变量记录要求的值
    static int maxSum;
};
int Solution::maxSum = INF;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值