leetcode Binary Tree Maximum Path Sum 迭代算法
来源:互联网 发布:西岐网络 编辑:程序博客网 时间:2024/06/03 08:15
Given a binary tree, find the maximum path sum.
The path may start and end at any node in the tree.
For example:
Given the below binary tree,
1 / \ 2 3
Return 6
.
这个是leetcode的一道题,一般给的是深搜的算法,这里用的是迭代实现,算法的主要思想是对于每一个节点,找到这个节点最长的路径,再用迭代额算法遍历整棵树,得到结果,理论上的时间复杂度是0(n2),但是没能AC,上代码,记住:后续遍历栈保存的是根节点到所访问节点的完整的路径
/** * 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 maxPathSums(TreeNode* root){if (root == NULL){return 0;}stack<TreeNode*> stk;TreeNode* p = root;TreeNode* prev = NULL;int result = 0;int sum = 0;while (p || !stk.empty()){if (p){stk.push(p);sum += p->val;p = p->left;}else{p = stk.top();if (p->right && p->right != prev){p = p->right;sum += p->val;stk.push(p);p = p->left;}else{result = max(result, sum);sum -= p->val;stk.pop();prev = p;p = NULL;}}}return result;}int sum(TreeNode* root){return maxPathSums(root->left) + maxPathSums(root->right) + root->val;}int maxPathSum(TreeNode *root){if (root == NULL){return 0;}stack<TreeNode*> stk;stk.push(root);int result = INT_MIN;while (!stk.empty()){TreeNode* p = stk.top();stk.pop();result = max(result, sum(p));if (p->right){stk.push(p->right);}if (p->left){stk.push(p->left);}}return result;}};
0 0
- leetcode Binary Tree Maximum Path Sum 迭代算法
- *****(leetcode) Binary Tree Maximum Path Sum (tree)
- LeetCode算法题目:Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [Leetcode] Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode Binary Tree Maximum Path Sum
- [LeetCode] Binary Tree Maximum Path Sum
- leetcode Binary Tree Maximum Path Sum
- 【leetcode】Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- [LeetCode]Binary Tree Maximum Path Sum
- [Leetcode]Binary Tree Maximum Path Sum
- Leetcode: Binary Tree Maximum Path Sum
- LeetCode-Binary Tree Maximum Path Sum
- [leetcode] Binary Tree Maximum Path Sum
- LeetCode - Binary Tree Maximum Path Sum
- LeetCode 124: Binary Tree Maximum Path Sum
- 推荐:《嵌入式系统开发之道:菜鸟成长日志与项目经理的私房菜》
- 设计简单的计算器-浙大2006年机试,参考王道机试指南
- HDU1097
- Codeforces Round #272 (Div. 2)AK报告
- java之变量以及对象的存储位置区别
- leetcode Binary Tree Maximum Path Sum 迭代算法
- Mac/Linux/Windows通过命令调用浏览器打开某网页
- 1410121949-hd-1sting
- 第7周项目--求两数的差值
- Max Points on a line ,在二维平面寻找共线的最多点
- 2035 人见人爱A^B
- 双系统启动引导项配置
- jquery——zTree, 完美好用的树插件
- UML关系(泛化,实现,依赖,关联(聚合,组合))