LeetCode | 515. Find Largest Value in Each Tree Row 广度优先遍历
2018-01-12 10:15
375 查看
Youneed to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
这一题很简单,广度优先遍历就能解决,但是想要时间最短可不容易,这里假如使用queue来实现广度优先遍历的话,时间会变长,当时假如使用list链表来实现广度优先遍历的话,时间会缩短很多,以后在做只涉及到头尾的操作的时候,使用List 链表会很快,比如以后在广度优先遍历的时候使用List 链表会很快
class Solution {
public:
vector<int> largestValues(TreeNode*root) {
vector<int> result;
if (root == NULL) return result;
queue< TreeNode *> store;
TreeNode* p;
store.push(root);
int t = 1;
int u = 0;
int max=INT_MIN;
while (!store.empty())
{
p = store.front();
store.pop();
t--;
if (p->val > max) max =p->val;
if (p->left != NULL) { store.push(p->left);u++; }
if (p->right != NULL) {store.push(p->right); u++; }
if (t == 0)
{
result.push_back(max);
t = u;
max = INT_MIN;
u = 0;
}
}
return result;
}
};
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
这一题很简单,广度优先遍历就能解决,但是想要时间最短可不容易,这里假如使用queue来实现广度优先遍历的话,时间会变长,当时假如使用list链表来实现广度优先遍历的话,时间会缩短很多,以后在做只涉及到头尾的操作的时候,使用List 链表会很快,比如以后在广度优先遍历的时候使用List 链表会很快
class Solution {
public:
vector<int> largestValues(TreeNode*root) {
vector<int> result;
if (root == NULL) return result;
queue< TreeNode *> store;
TreeNode* p;
store.push(root);
int t = 1;
int u = 0;
int max=INT_MIN;
while (!store.empty())
{
p = store.front();
store.pop();
t--;
if (p->val > max) max =p->val;
if (p->left != NULL) { store.push(p->left);u++; }
if (p->right != NULL) {store.push(p->right); u++; }
if (t == 0)
{
result.push_back(max);
t = u;
max = INT_MIN;
u = 0;
}
}
return result;
}
};
相关文章推荐
- leetcode 752. Open the Lock 开锁 + 十分典型的广度优先遍历BFS
- leetcode 116. Populating Next Right Pointers in Each Node BFS广度优先遍历
- 01 Matrix--广度优先遍历bfs--leetcode
- 广度优先遍历 之 LeetCode 542. 01 Matrix
- Leetcode - 广度优先遍历
- LeetCode Binary Tree Right Side View : 思想上的基于队列的广度优先遍历,形式上的一个简单变种
- Leetcode 之BFS广度优先遍历
- leetcode 515. Find Largest Value in Each Tree Row 二叉树每一层最大值+广度优先遍历BFS
- leetcode - 662. Maximum Width of Binary Tree【广度优先遍历 + 层次计数】
- leetcode 388. Longest Absolute File Path 最长长度文件路径 + 广度优先遍历BFS
- 【广度优先遍历】leetcode - Word Ladder II
- LeetCode 102. Binary Tree Level Order Traversal 树的广度优先遍历 辅助数据结构队列
- leetcode - 637. Average of Levels in Binary Tree【广度优先遍历 + 辅助变量】
- leetcode 637. Average of Levels in Binary Tree 二叉树每层平均值+广度优先遍历BFS
- 【图】图的邻接表存储和广度优先遍历
- 二叉树的深度优先,广度优先,以及层次遍历算法
- 图的深度优先遍历和广度优先遍历
- 图的深度优先遍历和广度优先遍历
- 图的广度优先遍历与深度优先遍历
- 数据结构实验之图论二:基于邻接表的广度优先搜索遍历