博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
LeetCode 124.Binary Tree Maximum Path Sum (二叉树中的最大路径和)
阅读量:2179 次
发布时间:2019-05-01

本文共 771 字,大约阅读时间需要 2 分钟。

题目描述:

给定一个非空二叉树,返回其最大路径和。

本题中,路径被定义为一条从树中任意节点出发,达到任意节点的序列。该路径至少包含一个节点,且不一定经过根节点。

示例 1:

输入: [1,2,3]       1      / \     2   3输出: 6

示例 2:

输入: [-10,9,20,null,null,15,7]   -10   / \  9  20    /  \   15   7输出: 42

 

 

AC C++ Solution:

解题思路:自下而上更新树的每个节点,返回子树的最大路径和,同时更新max值。

代码:

class Solution {public:    int maxPathSum(TreeNode* root) {        int max = INT_MIN;        maxToRoot(root,max);        return max;    }    private:    int maxToRoot(TreeNode *root, int &re) {        if(!root)   return 0;        int l = maxToRoot(root->left,re);        int r = maxToRoot(root->right,re);        if(l < 0)   l = 0;        if(r < 0)   r = 0;        if(l+r+root->val > re)  re = l + r + root->val; //遍历更新max值        return root->val + max(l,r);                    //向父节点返回子树的最大路径和    }};

 

 

 

 

 

 

 

转载地址:http://dgnkb.baihongyu.com/

你可能感兴趣的文章
【LEETCODE】9-Palindrome Number
查看>>
【极客学院】-python学习笔记-Python快速入门(面向对象-引入外部文件-Web2Py创建网站)
查看>>
【LEETCODE】190-Reverse Bits
查看>>
【LEETCODE】67-Add Binary
查看>>
【LEETCODE】7-Reverse Integer
查看>>
【LEETCODE】165-Compare Version Numbers
查看>>
【LEETCODE】299-Bulls and Cows
查看>>
【LEETCODE】223-Rectangle Area
查看>>
【LEETCODE】12-Integer to Roman
查看>>
【学习方法】如何分析源代码
查看>>
【LEETCODE】61- Rotate List [Python]
查看>>
【LEETCODE】143- Reorder List [Python]
查看>>
【LEETCODE】82- Remove Duplicates from Sorted List II [Python]
查看>>
【LEETCODE】86- Partition List [Python]
查看>>
【LEETCODE】147- Insertion Sort List [Python]
查看>>
【算法】- 动态规划的编织艺术
查看>>
用 TensorFlow 让你的机器人唱首原创给你听
查看>>
对比学习用 Keras 搭建 CNN RNN 等常用神经网络
查看>>
深度学习的主要应用举例
查看>>
word2vec 模型思想和代码实现
查看>>