Medium:Find Largest Value in Each Tree Row
来源:互联网 发布:ubuntu恢复初始命令 编辑:程序博客网 时间:2024/06/09 19:20
515. Find Largest Value in Each Tree Row
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]
代码如下:
class Solution {public: vector<int> largestValues(TreeNode* root) { if(root == NULL) return {}; vector<int> mac; queue<TreeNode*> q; queue<int> level; q.push(root); level.push(0); int m = -1; while (q.size()) { TreeNode *r = q.front(); q.pop(); int l = level.front(); level.pop(); if(r->left) { q.push(r->left); level.push(l+1); } if(r->right){ q.push(r->right); level.push(l+1); } if(l > m){ m = l; mac.push_back(r->val); } else { mac[l] = std::max(mac[l], r->val); } } return mac; }};
解题思路:
- 本题采用了BFS算法,利用队列q,level 以及向量 mac;
- q用来存放遍历到的结点,level记录当前结点出于哪一层,mac则存放每一层的最大值;
- 当两个结点处于不同层时,直接压入队列q;若出于同一层,则与原有值进行对比,把较大的那一个存入该位置。
0 0
- 515. Find Largest Value in Each Tree Row(Medium)
- Medium:Find Largest Value in Each Tree Row
- LeetCode 515. Find Largest Value in Each Tree Row [Medium]
- 515. Find Largest Value in Each Tree Row Difficulty: Medium
- 515[Medium]:Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Find Largest Value in Each Tree Row
- Leetcode: 515.Find Largest Value in Each Tree Row(Week10, Medium)
- Tree——Find Largest Value in Each Tree Row
- LeetCode 515. Find Largest Value in Each Tree Row
- 515. Find Largest Value in Each Tree Row
- 对抗生成网络(文献、教程、模型、框架、库等)
- Laravel No supported encrypter found. The cipher and / or key length are invalid
- 这是目前在做的事情的进度
- Android状态模式实践
- 三大常用机密算法原理与基础使用MD5、3DES、RSA
- Medium:Find Largest Value in Each Tree Row
- matplotlib的基本用法(八)——绘制柱状图
- 神经网络压缩(3):Learning both Weights and Connections for Efficient Neural Network
- 周志华《机器学习》课后习题解答系列(六):Ch5.8
- 老司机带你探知存储伸缩之道
- LwIP源代码文件目录解析
- 编码解码
- 数据结构简单应用
- Java对MySQL中的数据实现增查删改