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

来源:互联网 发布:素描入门 知乎 编辑:程序博客网 时间:2024/05/21 15:07

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 0x80000000class 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;
0 0
原创粉丝点击