Given a non-empty 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 must contain at least one node and does not need to go through the root.

Example 1:

Input: [1,2,3]

       1
/ \
2 3 Output: 6

Example 2:

Input: [-10,9,20,null,null,15,7]

   -10
   / \
  9  20
    /  \
   15   7 Output: 42
  

这道求二叉树的最大路径和是一道蛮有难度的题,难就难在起始位置和结束位置可以为任意位置,博主当然是又不会了,于是上网看看大神们的解法,像这种类似树的遍历的题,一般来说都需要用 DFS 来求解,先来看一个简单的例子:

   / \

 / \
   

由于这是一个很简单的例子,很容易就能找到最长路径为 7->11->4->13,那么怎么用递归来找出正确的路径和呢?根据以往的经验,树的递归解法一般都是递归到叶节点,然后开始边处理边回溯到根节点。这里就假设此时已经递归到结点7了,其没有左右子节点,如果以结点7为根结点的子树最大路径和就是7。然后回溯到结点 11,如果以结点 11 为根结点的子树,最大路径和为 7+11+2=20。但是当回溯到结点4的时候,对于结点 11 来说,就不能同时取两条路径了,只能取左路径,或者是右路径,所以当根结点是4的时候,那么结点 11 只能取其左子结点7,因为7大于2。所以,对于每个结点来说,要知道经过其左子结点的 path 之和大还是经过右子节点的 path 之和大。递归函数返回值就可以定义为以当前结点为根结点,到叶节点的最大路径之和,然后全局路径最大值放在参数中,用结果 res 来表示。

在递归函数中,如果当前结点不存在,直接返回0。否则就分别对其左右子节点调用递归函数,由于路径和有可能为负数,这里当然不希望加上负的路径和,所以和0相比,取较大的那个,就是要么不加,加就要加正数。然后来更新全局最大值结果 res,就是以左子结点为终点的最大 path 之和加上以右子结点为终点的最大 path 之和,还要加上当前结点值,这样就组成了一个条完整的路径。而返回值是取 left 和 right 中的较大值加上当前结点值,因为返回值的定义是以当前结点为终点的 path 之和,所以只能取 left 和 right 中较大的那个值,而不是两个都要,参见代码如下:

class Solution {
public:
int maxPathSum(TreeNode* root) {
int res = INT_MIN;
helper(root, res);
return res;
}
int helper(TreeNode* node, int& res) {
if (!node) return ;
int left = max(helper(node->left, res), );
int right = max(helper(node->right, res), );
res = max(res, left + right + node->val);
return max(left, right) + node->val;
}
};

讨论:这道题有一个很好的 Follow up,就是返回这个最大路径,那么就复杂很多,因为这样递归函数就不能返回路径和了,而是返回该路径上所有的结点组成的数组,递归的参数还要保留最大路径之和,同时还需要最大路径结点的数组,然后对左右子节点调用递归函数后得到的是数组,要统计出数组之和,并且跟0比较,如果小于0,和清零,数组清空。然后就是更新最大路径之和跟数组啦,还要拼出来返回值数组,代码长了很多,有兴趣的童鞋可以在评论区贴上你的代码~

Github 同步地址:

https://github.com/grandyang/leetcode/issues/124

类似题目:

Path Sum

Sum Root to Leaf Numbers

Path Sum IV

Longest Univalue Path

参考资料:

https://leetcode.com/problems/binary-tree-maximum-path-sum/

https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/39775/Accepted-short-solution-in-Java

https://leetcode.com/problems/binary-tree-maximum-path-sum/discuss/39869/Simple-O(n)-algorithm-with-one-traversal-through-the-tree

LeetCode All in One 题目讲解汇总(持续更新中...)

[LeetCode] 124. Binary Tree Maximum Path Sum 求二叉树的最大路径和的更多相关文章

  1. [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. ...

  2. leetcode 124. Binary Tree Maximum Path Sum 、543. Diameter of Binary Tree(直径)

    124. Binary Tree Maximum Path Sum https://www.cnblogs.com/grandyang/p/4280120.html 如果你要计算加上当前节点的最大pa ...

  3. 第四周 Leetcode 124. Binary Tree Maximum Path Sum (HARD)

    124. Binary Tree Maximum Path Sum 题意:给定一个二叉树,每个节点有一个权值,寻找任意一个路径,使得权值和最大,只需返回权值和. 思路:对于每一个节点 首先考虑以这个节 ...

  4. [leetcode]124. Binary Tree Maximum Path Sum二叉树最大路径和

    Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as any ...

  5. LeetCode 124. Binary Tree Maximum Path Sum 二叉树中的最大路径和 (C++/Java)

    题目: Given a non-empty binary tree, find the maximum path sum. For this problem, a path is defined as ...

  6. leetcode 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 ...

  7. leetcode 124. Binary Tree Maximum Path Sum ----- java

    Given a binary tree, find the maximum path sum. For this problem, a path is defined as any sequence ...

  8. leetcode@ [124] Binary Tree Maximum Path Sum (DFS)

    https://leetcode.com/problems/binary-tree-maximum-path-sum/ Given a binary tree, find the maximum pa ...

  9. [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. ...

随机推荐

  1. WIN7快速打开hosts方法

    WIN7快速打开hosts方法 1直接运行C:\Windows\System32\drivers\etc\hosts 浏览选择notepad++打开即可 2打开notepad++打开 C:\Windo ...

  2. $.Ajax、$.Get、$.Post代码实例参数解析

    $.ajax 语法: $.ajax({name:value, name:value, ... }) 示例: $.ajax({ url: "/testJson", type: &qu ...

  3. Redis set集合

    Set操作.Set集合就是不允许重复的列表 (无序集合) sadd(name,values) # name对应的集合中添加元素 scard(name) # 获取name对应的集合中元素个数 sdiff ...

  4. 专栏《Elasticsearch 7.x从入门到精通》的相关源代码

    新版Elasticsearch 7.3 和 Spring Boot 2.1.7 集成演示项目       第一个项目:演示Elasticsearch 6.4.3 和Spring Boot 2.1.7集 ...

  5. Python - 输入和输出 - 第十七天

    Python 输入和输出 在前面几个章节中,我们其实已经接触了 Python 的输入输出的功能.本章节我们将具体介绍 Python 的输入输出. 输出格式美化 Python两种输出值的方式: 表达式语 ...

  6. PhantomJS简单使用

    PhantomJS下载地址:   http://phantomjs.org/download.html 简单使用: from selenium import webdriver # 要想调用键盘按键操 ...

  7. Mysql、Oracle、SQLServer等数据库参考文档免费分享下载

    场景 MySQL 是最流行的关系型数据库管理系统,在 WEB 应用方面 MySQL 是最好的 RDBMS(Relational Database Management System:关系数据库管理系统 ...

  8. 快速上手Mac效率神器Alfred以及Alfred常用操作

    前言 Alfred,想必大家就算没用过也耳闻过.Alfred是一个让你可以丢掉鼠标的神器.很多读者可能之前认为Alfred的学习成本高,或者感觉它太复杂,而望之却步.其实Alfred并非高不可攀,本文 ...

  9. C# 常用类库(字符串处理,汉字首字母拼音,注入攻击,缓存操作,Cookies操作,AES加密等)

    十年河东,十年河西,莫欺少年穷 学无止境,精益求精 记录下字符串类库,方便今后查阅 主要包含了字符串解决,去除HTML,SQL注入攻击检测,IP地址处理,Cookies操作,根据身份证获取性别.姓名. ...

  10. 【转载】Visual Studio2017如何设置打包发布的WinForm应用程序的版本号

    在Visual Studio 2017集成开发工具中,打包发布Winform窗体应用程序的时候,支持设置此次打包发布的Winform窗体应用程序对应的版本号信息,并且支持一次设置后,后续的所有发布版本 ...