博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C++ leetcode Binary Tree Maximum Path Sum
阅读量:6913 次
发布时间:2019-06-27

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

偶然在面试题里面看到这个题所以就在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 = -9999999;     int maxPathSum(TreeNode* root) {        maxpath(root);        return MAX;    }    int maxpath(TreeNode *node){        if(node == NULL)            return 0;        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;        }    }    };

 

转载于:https://www.cnblogs.com/catpainter/p/8526932.html

你可能感兴趣的文章
mac终端下svn常用命令
查看>>
C++的lambda表达式
查看>>
新手学习python(十六)封装redis
查看>>
vue移动端弹框组件
查看>>
vuex
查看>>
vux 全局使用 loading / toast / alert
查看>>
面向对象数组操作
查看>>
Cocos2d-x之内存管理
查看>>
Sharepoint 列表分页开发
查看>>
当页面是本地页面时,通过ajax访问tomcat里的action,传递的参数在action里并不能识别...
查看>>
RocketMQ Java 客户端实现
查看>>
hdu 1133 Buy the Ticket (大数+递推)
查看>>
java:Java里数字转字符串前面自动补0的实现
查看>>
获取图片颜色的rgb,以供css设计背景颜色
查看>>
org.tinygroup.validate-验证框架
查看>>
人脸识别中的harr特征提取(转)
查看>>
Windows 8 Metro App开发[6]访问Assets文件夹
查看>>
Cpython的全局解释器锁(GIL)
查看>>
session共享方法
查看>>
ASP.NET AJAX web chat application
查看>>