Binary Tree Maximum Path Sum
来源:互联网 发布:陕西省大数据集团股东 编辑:程序博客网 时间:2024/06/06 00:07
弄清楚这道题中的path指的是什么是成功的关键。我就是在没弄清楚题意的情况下做了半天无用功。。。
这里的path指的是从树中的一个节点开始,沿着边走到另一个节点位置,所经历的所有节点组成一个path,同一个节点不能在path中出现2次,其实就是图中的path。
程序主体主需要对树进行一次dfs即可,在每个节点都要做一个决策:是否要从当前节点继续沿parent路径往上返回;如果返回,则最佳路径的决策留待上层解决;如果不返回,那么在当前节点处解决最佳路径。
pathStart返回的是以参数root为path的一端,另一端在root以下寻找,所能找到的最佳路径。
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: int res; int pathStart(TreeNode* root) { if((root->left==NULL)&&(root->right==NULL)) { if(root->val>res) { res=root->val; } return root->val; } int tmp=root->val;//save the value need to be further checked along parent path int curVal=root->val;//save the value do not need to be further checked along parent path if(root->left!=NULL) { //extend to left child int v=pathStart(root->left); if(v>=0) { if((root->val+v)>tmp) { tmp=root->val+v; } curVal+=v; } } if(root->right!=NULL) { //extend to right child int v=pathStart(root->right); if(v>=0) { if((root->val+v)>tmp) { tmp=root->val+v; } curVal+=v; } } if(curVal>res) { res=curVal; } //extend to parent return tmp; } int maxPathSum(TreeNode *root) { res=-(1<<31); if(root==NULL) { return 0; } int tmp=pathStart(root); if(tmp>res) { res=tmp; } return res; }};
0 0
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- Binary Tree Maximum Path Sum
- UML Dependency Association Aggregation Composition Generalization Realization
- Robotium中文API(29)-solo.waitForWebElement
- Codeforces 508E Arthur and Brackets
- 用Word做一个漂亮的网页
- Qt 5.4 + OpenCV 进行图像处理Tips
- Binary Tree Maximum Path Sum
- iOS:界面适配(1)--iPhone不同机型适配 6/6plus 前
- 使用Apache配置Tomcat应用整合PHP论坛-Discuz
- Windows下搭建WordPress测试环境
- Java语言基础——壹
- eclipse uml
- Android众多的布局属性详解
- 关于前两篇获取session问题的总结!
- android 数据存储操作2:SharedPreferences