二叉树的最长路径和(Binary Tree Maximum Path Sum)

0 阅读 作者:magicianofcodes 2017-10-18

题目:

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 must contain at least one node and does not need to go through the root
google 翻译:
给定一个二叉树,找到最大路径和。 对于这个问题,路径被定义为从父子连接到某个起始节点到树中任何节点的任何节点序列。 该路径必须包含至少一个节点,不需要遍历根。
示例:
这里写图片描述

就是从任意节点开始到任意节点结束所走过的最大距离

思路:
最大值的可能情况,虽然题目说不需要遍历根节点,其实是需要根节点的。
把根节点理解成父节点更好一些,因为需要父节点和别的连成一条线。
最大值来自

  1. root+左边的某条路径+右边的某条路径
  2. 左边的某条路径 + root
  3. root + 右边的某条路径
  4. root
    练习传送门:这里

java实现:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    int max = Integer.MIN_VALUE;
    public int maxPathSum(TreeNode root) {
        record(root);
        return max;
    }
    public int record(TreeNode root){
        if(root==null) return 0;
        int l=Math.max(0,record(root.left));
        int r=Math.max(0,record(root.right));
        max=Math.max(max,root.val+l+r);
        return root.val+Math.max(l,r);
    }
}
原文地址:http://blog.csdn.net/magicianofcodes/article/details/78194806
广告一下
热门教程
PHP7报A non well formed numeric value encountered 0
Linux系统下关闭mongodb的几种命令分享 0
mongodb删除数据、删除集合、删除数据库的命令 0
Git&Github极速入门与攻坚实战课程 0
python爬虫教程使用Django和scrapy实现 0
libnetsnmpmibs.so.31: cannot open shared object file 0
数据结构和算法视频教程 0
redis的hash结构怎么删除数据呢? 0
C++和LUA解析器的数据交互实战视频 0
mongodb errmsg" : "too many users are authenticated 0
C++基础入门视频教程 0
用30个小时精通C++视频教程可能吗? 0
C++分布式多线程游戏服务器开发视频教程socket tcp boost库 0
C++培训教程就业班教程 0
layui的util工具格式时间戳为字符串 0
C++实战教程之远程桌面远程控制实战 1
网络安全培训视频教程 0
LINUX_C++软件工程师视频教程高级项目实战 0
C++高级数据结构与算法视频教程 0
跨域问题很头疼?通过配置nginx轻松解决ajax跨域问题 0
相关文章
【译】JavaScript数据结构(3):单向链表与双向链表 16
10个JavaScript难点 16
【译】苹果拒绝支持PWA,有损Web的未来 16
iView 一周年了,同时发布了 2.0 正式版,但这只是开始... 16
nodejs+mongodb构建一个简单登录注册功能 16
【译】JavaScript数据结构(4):树 16
组件化开发与黑箱 16
TypeScript - 不止稳,而且快 16
webpack3+anujs+ReactCSSTransitionGroup 16
原生js实现图片放大镜效果 16
WEB缓存探究第二弹——实战 16
纯笔记:vfork 的一些使用场景(顺便讲一下 fork 的原理) 16
Android APP 内部捐赠实现(支付宝&微信) 16
WKWebView 的一些小总结 16
模型评价(一) AUC大法 16
开始使用GraphQL 16
Webpack模块化原理简析 16
gulp使用问题记录 16
使用Angular4动画为页面添彩 16
Python27 Matplotlib (win64 python2.7) 安装及简单使用 16