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. 论反馈信息如何推动 IT 运维团队进步?

    我们还记得<快乐大本营>中经典游戏----快乐传真吗?游戏规则是:很多人站一排,只有第一个人才看到最准确的信息,用东西隔着,戴耳机,一一将从前一个人获得的信息传递下去,最后一个人说出推测的 ...

  2. html10个特效(转载)

    http://www.html5tricks.com/10-html5-jquery-image-animatin.html 现在网页上的图片已经不再是10几年前那种低像素的静态图片了,有了HTML5 ...

  3. windows 下 文件属性及目录列表操作

    转:http://blog.sina.com.cn/s/blog_686d0fb001012tsg.html 我们需要一个结构体和几个函数.这些函数和结构体在<io.h>的头文件中,结构体 ...

  4. Trainning Guide, Data Structures, Example

    最近在复习数据结构,发现这套题不错,题目质量好,覆盖广,Data Structures部分包括Example,以及简单,中等,难三个部分,这几天把Example的做完了, 摘要如下: 通过这几题让我复 ...

  5. 完全掌握Android Data Binding

    转载:http://www.jcodecraeer.com/a/anzhuokaifa/androidkaifa/2015/0603/2992.html 来源 https://github.com/L ...

  6. C#+SQL数据库备份和还原

    使用前要导入SQLDMO.dll(在com组件中导入Microsoft SQLDMO Object Library即可) /// /// DbOper类,主要应用SQLDMO实现对Microsoft ...

  7. P151、面试题27:二叉搜索树与双向链表

    题目:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表.要求不能创建任何新的结点,只能调整树中结点指针的指向.(本质是中序遍历)二叉树结点的定义如下:struct BinaryTreeNod ...

  8. 【原创】通俗易懂的讲解KMP算法(字符串匹配算法)及代码实现

    一.本文简介 本文的目的是简单明了的讲解KMP算法的思想及实现过程. 网上的文章的确有些杂乱,有的过浅,有的太深,希望本文对初学者是非常友好的. 其实KMP算法有一些改良版,这些是在理解KMP核心思想 ...

  9. mongoDB入门必读

    一.概述 MongoDB是一个基于分布式文件存储的数据库开源项目. 由C++语言编写,旨在为WEB应用提供可护展的高性能数据存储解决方案. MongoDB是一个介于关系数据库和非关系数据库之间的产品. ...

  10. S5P4418 uboot 分析

    瘋耔新浪微博:   http://weibo.com/cpjphone 一: 1◑ 从链接脚本文件u-boot.lds('/opt/4418-source/android/u-boot' )中可以找到 ...