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. Uboot启动流程分析(二)

    1.前言 在前面的文章Uboot启动流程分析(一)中,链接如下: https://www.cnblogs.com/Cqlismy/p/12000889.html 已经简单地分析了low_level_i ...

  2. 【前端知识体系-NodeJS相关】NodeJS高频前端面试题整理

    1. 为什么JavaScript是单线程? 防止DOM渲染冲突的问题: Html5中的Web Worker可以实现多线程 2.什么是任务队列? 任务队列"是一个先进先出的数据结构,排在前面的 ...

  3. Vue.js 源码分析(三十二) 总结

    第一次写博客,坚持了一个多月时间,Vue源码分析基本分析完了,回过头也看也漏了一些地方,比如双向绑定里的观察者模式,也可以说是订阅者模式,也就是Vue里的Dep.Watcher等这些函数的作用,网上搜 ...

  4. HTTP Error 502.5 - ANCM Out-Of-Process Asp.Net Core发布到IIS失败

    问题概述 asp.net core网站发布到windows server 2012r2 IIS后,出现这个报错.dotnet xx.dll命令网站能够正常运行.说明不是程序问题. 经过一番折腾终于部署 ...

  5. C#循环结构

    一.背景: 因编程的基础差,因此最近开始巩固学习C#基础,后期把自己学习的东西,总结相应文章中,有不足处请大家多多指教. 二.简介 有的时候,可能需要多次执行同一块代码.一般情况下,语句是顺序执行的: ...

  6. Asp.Net真分页技术

    最近学校要做课题,闲来没事研究了下Asp.net的分页,我使用Repeater进行数据的绑定,每次从数据库读取到8条数据填充到Repeater中,这样搞可以降低数据库的压力,提高效率. 效果图如下: ...

  7. ASP.NET MVC过滤器学习笔记

    1.过滤器的两个特征 1.他是一种特性,可以引用到控制器类和Action方法上.比如下图 这里控制器类和action方法都引用了过滤器,这个过滤器是用来做授权的 2.特征继承自FilterAttrib ...

  8. swift(一)基础变量类型

    import Foundation println("Hello, World!") /* int a; */ var a = //隐式类型转换 a = println(a) le ...

  9. 简单聊聊实时视频rtmp

    背景: 由于经常接触实时视频, 对实时视频略有了解. 实时视频是将视频流实时上传到服务器端进行解析, 由RTMP服务器处理. RTMP 服务器 自己动手搭建一个rtmp, 本文在 Linux环境中搭建 ...

  10. pandas 之 交叉表-透视表

    import numpy as np import pandas as pd 认识 A pivot table is a data summarization tool(数据汇总工具) frequen ...