首页 技术 正文
技术 2022年11月17日
0 收藏 788 点赞 5,101 浏览 1216 个字

偶然在面试题里面看到这个题所以就在Leetcode上找了一下,不过Leetcode上的比较简单一点。

题目:

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.

For example:
Given the below binary tree,

       1
/ \
2 3

Return 6.

暴力解法就是将每一个节点作为开始节点,寻找最大的路径长度,感觉和在一个整数序列中寻找和最大的子序列差不多,不同的是每一个开始节点有几条不同的路。再仔细想一想就知道,每一条路径肯定都有一个最高的节点,把每一个节点作为一条路径的最高节点并且是这个路径的末端节点,可以应用递归来解决这个问题。假设节点x为这条路径的最高节点和末端节点,求得这条路径的函数为maxpath(x)=max(maxpath(x->left)+x->val, maxpath(x->right)+x->val, x->val) 。调用根节点的maxpath可以计算出以每个节点为最高节点和末端节点的路径的最大值,那以该节点为最高节点的路径的最大值为maxpath(x)或者maxpath(x->left)+maxpath(x->right)+x->val,可以用MAX记录这个值,最后函数返回MAX

/**
* 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 MAX = -;
int maxPathSum(TreeNode* root) {
maxpath(root);
return MAX;
}
int maxpath(TreeNode *node){
if(node == NULL)
return ;
else{
int x = maxpath(node->left), y = maxpath(node->right);
int maxlen = x+node->val > node->val? x+node->val:node->val;
int result = maxlen > y+node->val?maxlen:y+node->val;
MAX = result>MAX?result:MAX;
MAX = x+y+node->val>MAX? x+y+node->val:MAX;
return result;
}
}};
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,498
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,135
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,299