首页 技术 正文
技术 2022年11月6日
0 收藏 490 点赞 793 浏览 1151 个字

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 does not need to go through the root.

For example:
Given the below binary tree,

       1
/ \
2 3

Return 6.

=============

题目:树中联通路径中,路径元素和最大值?

路径利用父子关系相连,不必经过根节点root

路径可以从任意节点开始,到任意节点.

=====

思路:

这道题的解法,来自网络leetcode150题集合,

利用dfs遍历树的方式,传递每个树父子节点间的路径大小;

利用一个全局遍历来时记住max_sum来记录已经找到的最大的路径值,

最难理解的是怎么在 dfs遍历树的过程,传递路径信息?

—–

借用”最大连续子序列和”问题的思路,array只有一个方向,

但是Tree有左右两个方向,我们需要比较两个方向上的值.

先算出左右子树的结果L和R.

  如果L>0,那么对后序结果是有利的,后序中加上L,(不是向max_sum中,而是向如节点中)

  如果R>0,那么对后序结果是有利的,加上R

==========

代码如下:

/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
///
int help_maxPathSum(int &max_sum,TreeNode *root){
if(root==nullptr) return ;
int l = help_maxPathSum(max_sum,root->left);
int r = help_maxPathSum(max_sum,root->right);
int sum = root->val;
if(l>) sum += l;
if(r>) sum += r;
max_sum = max(max_sum,sum);
return max(r,l)>? max(r,l)+root->val:root->val;//只能向上传递 左子树或者 右子树的有利值
}
int maxPathSum(TreeNode* root) {
int max_sum = INT_MIN;
help_maxPathSum(max_sum,root);
return max_sum;
}
};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,086
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,561
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,410
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,183
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,820
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,903