第十二周算法分析与设计: Find Largest Value in Each Tree Row
2017-05-11 19:01
423 查看
问题描述:
You need to find the largest value in each row of a binary tree.
Example:
Input:
Output: [1, 3, 9]
解法思路:
跟第十周的算法思路类似,在层次遍历时记下每个节点——当到达新一层时,将当前节点的值放入vector中;在之后的同层遍历中,如果有比它大的就替换。
算法的执行时间复杂度为O(n)。
休息下,这波不亏~
You need to find the largest value in each row of a binary tree.
Example:
Input:
1 / \ 3 2 / \ \ 5 3 9
Output: [1, 3, 9]
解法思路:
跟第十周的算法思路类似,在层次遍历时记下每个节点——当到达新一层时,将当前节点的值放入vector中;在之后的同层遍历中,如果有比它大的就替换。
class Solution { public: vector<int> largestValues(TreeNode* root) { vector<int> result; if(root != NULL) { queue<int>level; queue<TreeNode*>node; node.push(root); level.push(1); result.push_back(root->val); int m = 1; while(!node.empty()) { TreeNode* cur_n = node.front(); int cur_l = level.front(); if(cur_n->left) { node.push(cur_n->left); level.push(cur_l+1); } if(cur_n->right) { node.push(cur_n->right); level.push(cur_l+1); } node.pop(); level.pop(); if(m == cur_l) { if(cur_n->val > result[m-1]) result[m-1] = cur_n->val; } else { m++; result.push_back(cur_n->val); } } } return result; } };
算法的执行时间复杂度为O(n)。
休息下,这波不亏~
相关文章推荐
- 算法分析与设计丨第三周丨LeetCode(6)——Find Largest Value in Each Tree Row(Medium)
- Find Largest Value in Each Tree Row宽度优先遍历算法详解
- LeetCode算法问题17 —— Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- 515[Medium]:Find Largest Value in Each Tree Row
- 【LeetCode】Find Largest Value in Each Tree Row 解题报告
- 【LeetCode515 Find Largest Value in Each Tree Row】二叉树每行的最大值
- Find Largest Value in Each Tree Row(找出一棵树每一行的最大值)
- LeetCode #515: Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- LeetCode:Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- LeetCode 515 Find Largest Value in Each Tree Row(二叉树层序遍历)
- leetcode515: Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- [LeetCode] Find Largest Value in Each Tree Row 找树每行最大的结点值
- LeetCode#515 Find Largest Value in Each Tree Row
- [LeetCode]515 Find Largest Value in Each Tree Row(dfs)
- LeetCode--Find Largest Value in Each Tree Row