1.题目说明

Given a binary tree, find the maximum path sum.

 

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

 

For example:

Given the below binary tree,

 

       1

      / \

     2   3

Return 6.

 

2.解法分析:

leetcode中给出的函数头为:int maxPathSum(TreeNode *root)

给定的数据结构为:

Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

乍一看这道题我就递归,每一条路径都会有一个最高节点,整棵树的最高节点是root,因此,对整棵树而言,和最长的路径只有三种情况:

  • 路径的最高节点为root
  • 路径的最高节点在root的左子树中
  • 路径的最高节点在root的右子树中

所以,这题可以递归来做,需要考虑的是路径中至少有一个节点,不能是空路径,这会给编码带来一定的麻烦,而且,虽然有了刚才的三个分类,怎么求三种情况下的最长路径呢?我们定义从节点A往下走一直到根部(可以不到根部)的路径中和最大的这个值为rootStartPathMaxSum(A),那么必然有,:

  • 如果路径的最高节点经过了root:理论上最大值为max(0,rootStartPathMaxSum(root->left) )+max(0,rootStartPathMaxSum(root->right) ) +root->val;
  • 如果路径的最高节点在root,递归计算
  • 如果路径的最高节点在root右侧,递归计算

最后比较这三种得出的值即可。

rootStartPathMaxSum(TreeNode *)这个函数的计算我最开始的算法是递归的。于是得出了下面一份代码。

/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    int maxPathSum(TreeNode *root) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if(root == NULL)return 0;

        if(root->left == NULL && root->right == NULL)

        {

            return root->val;

        }

        

        int case_both_side = max(0,rootStartPathMaxSum(root->left))+max(0,rootStartPathMaxSum(root->right))+root->val;

        

        if(root->left!=NULL && root->right == NULL)

        {

            return max(case_both_side,maxPathSum(root->left));

        }

        

        if(root->left==NULL && root->right != NULL)

        {

            return max(case_both_side,maxPathSum(root->right));

        }

        

        else

            return max(max(maxPathSum(root->left),maxPathSum(root->right)),case_both_side);

        

    }

    

    // 从root开始往根出发的和最长路径,不一定要到达根部

    int rootStartPathMaxSum(TreeNode *root)

    {

        if(root == NULL)return 0;

        

        if(root->left == NULL&& root->right == NULL)return root->val;

        

        if(root->left == NULL && root->right != NULL)

        {

            return max(root->val,root->val+rootStartPathMaxSum(root->right));

        }

        

        if(root->left != NULL && root->right ==NULL)

        {

            return max(root->val,root->val+rootStartPathMaxSum(root->left));

        }

        

        return max(max(rootStartPathMaxSum(root->left)+root->val,rootStartPathMaxSum(root->right)+root->val),root->val);

    }

};

 

在小数据集上运行良好,但是一到大数据集就hold不住了,运行结果如下:

其实写的过程就意识到了rootStartPathMaxSum有很多次被重复调用,于是得采用一种自底向上的算法,自己想了半天没想出来,结果网上搜到了一个神代码,我承认,很精妙,记录一下,学习一下:

/**

 * Definition for binary tree

 * struct TreeNode {

 *     int val;

 *     TreeNode *left;

 *     TreeNode *right;

 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}

 * };

 */

class Solution {

public:

    int maxPathSum(TreeNode *root) {

        // Start typing your C/C++ solution below

        // DO NOT write int main() function

        if (root == NULL)

            return 0;

        int max = root->val;

        getPathSum(root, max);

        return max;

    }

 

private:

    int getPathSum(TreeNode *root, int &max) {

        if (root == NULL)

            return 0;

        int leftSum = getPathSum(root->left, max);

        int rightSum = getPathSum(root->right, max);

        if (leftSum + root->val + rightSum > max)

            max = leftSum + root->val + rightSum;

        int subPathSum = leftSum > rightSum ? leftSum : rightSum;

        subPathSum += root->val;

        return subPathSum > 0 ? subPathSum : 0;

    }

};

转载自:http://blog.csdn.net/niaokedaoren/article/details/8798528

 

总的来说,我的算法思路跟这位是一样的,可惜实现思路的功底却差了很多,加油!


后记: 回去略微思索,上述思路中用一个max记录了当前最大值,leftsum和rightSum正是我所想追求的自底向上的中间变量,学习了,不过我的算法的有点事可以用两个中间变量保存起点和终点,这样就有利于路径记录。

leetcode–Binary Tree Maximum Path Sum的更多相关文章

  1. [leetcode]Binary Tree Maximum Path Sum

    Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start and ...

  2. LeetCode: Binary Tree Maximum Path Sum 解题报告

    Binary Tree Maximum Path SumGiven a binary tree, find the maximum path sum. The path may start and e ...

  3. 二叉树系列 - 二叉树里的最长路径 例 [LeetCode] Binary Tree Maximum Path Sum

    题目: Binary Tree Maximum Path Sum Given a binary tree, find the maximum path sum. The path may start ...

  4. [LeetCode] 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. ...

  5. C++ leetcode Binary Tree Maximum Path Sum

    偶然在面试题里面看到这个题所以就在Leetcode上找了一下,不过Leetcode上的比较简单一点. 题目: Given a binary tree, find the maximum path su ...

  6. [LeetCode] 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. ...

  7. [leetcode]Binary Tree Maximum Path Sum @ Python

    原题地址:https://oj.leetcode.com/problems/binary-tree-maximum-path-sum/ 题意: Given a binary tree, find th ...

  8. [Leetcode] 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. ...

  9. LeetCode Binary Tree Maximum Path Sum 二叉树最大路径和(DFS)

    题意:给一棵二叉树,要求找出任意两个节点(也可以只是一个点)的最大路径和,至少1个节点,返回路径和.(点权有负的.) 思路:DFS解决,返回值是,经过从某后代节点上来到当前节点且路径和最大的值.要注意 ...

随机推荐

  1. centos64位安装32位C/c++库

    yum install glibc.i686 glibc-devel.i686 yum install libstdc++.i686yum install libstdc++-devel.i686yu ...

  2. HTML可编辑下拉框

    <div style="position:relative;">   <select style="width:120px;" onchang ...

  3. STM32移植UCGUI3.90笔记

    在MDK环境下,终于将3.90版本的UCGUI移植到STM32下了,在网上看到的都是例程代码,很少看到有关于在STM32下移植UCGUI的教程方法,为了方便大家,特写此移植方法,大家可以借鉴(有错误之 ...

  4. secureCRT中文字符乱码

    1.远程linux机器.修改环境变量LANG.例如在~/.bash_profile里面添加 export LANG=zh_CN.UTF8 2.本地windows机器.修改SecureCRT的设置.找到 ...

  5. 找出程序cpu使用率高的原因

    确定是CPU过高 使用top观察是否存在CPU使用率过高现象 找出线程 对CPU使用率过高的进程的所有线程进行排序 ps H -e -o pid,tid,pcpu,cmd --sort=pcpu |g ...

  6. Git教程之标签管理

    发布一个版本时,我们通常先在版本库中打一个标签,这样,就唯一确定了打标签时刻的版本.将来无论什么时候,取某个标签的版本,就是把那个打标签的时刻的历史版本取出来.所以,标签也是版本库的一个快照.Git的 ...

  7. (从终端看linux-2)浅析terminal创建时ptmx和pts关系

    我们打开一个terminal,那么将会在devpts文件系统/dev/pts下创建一个对应的pts字符文件,该pts字符文件节点直接由/dev/ptmx节点的驱动函数ptmx_open()调用devp ...

  8. WCF的通信

    [ServiceContract]    public interface IContractDemoOne    {        [OperationContract(IsOneWay=true) ...

  9. node.js EventEmitter发送和接收事件

    EventEmitter是nodejs核心的一部分.很多nodejs对象继承自EventEmitter,用来处理事件,及回调.api文档地址: http://nodejs.org/api/events ...

  10. PHP session过期时间

    如何设置一个严格30分钟过期的Session 今天在我的微博(Laruence)上发出一个问题: 我在面试的时候, 经常会问一个问题: “如何设置一个30分钟过期的Session?”, 大家不要觉得看 ...