Leetcode / C++ / 515. Find Largest Value in Each Tree Row 结题报告+源代码
来源:互联网 发布:知乎日本反战同盟 编辑:程序博客网 时间:2024/06/11 10:51
思路:
典型的【广度优先搜索 BFS】。用一个queue实现,每次用curLen记录当前层的节点个数,然后依次取出,维护一个最大值,同时将此节点左右子节点也存到queue末尾。直到一层所有节点全部计数完毕,然后存到vector中,再进行下一层的统计。
AC代码:
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public: vector<int> largestValues(TreeNode* root) { vector<int> res; if(!root) return res; queue<TreeNode*> q; q.push(root); while(!q.empty()){ int curMax = INT_MIN; const int curLen = q.size();//局部const变量,在下一轮就会被更新 for(int i = 0; i < curLen; ++i){ TreeNode* cur = q.front(); curMax = max(curMax, cur->val); if(cur->left) q.push(cur->left); if(cur->right) q.push(cur->right); q.pop();//std::queue 只负责管理和使用,不负责成员内存释放,所以可以pop之后还使用front的那个指针。不过为了不混和易于理解淆,此处最后再pop。 } res.push_back(curMax); } return res; }};
0 0
- Leetcode / C++ / 515. Find Largest Value in Each Tree Row 结题报告+源代码
- LeetCode 515. Find Largest Value in Each Tree Row (C++)
- [LeetCode] [C++] 515. 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 OJ 515. 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
- 【LeetCode】515. 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
- leetcode 515. 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
- leetcode 515. 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
- LeetCode#515. Find Largest Value in Each Tree Row
- 串口使用中断发送字符串,并在LCD显示内容
- Kafka文件的存储机制
- 谈自动化测试框架思想与构建
- 欢迎使用CSDN-markdown编辑器
- MySQL中ON DUPLICATE KEY UPDATE语法
- Leetcode / C++ / 515. Find Largest Value in Each Tree Row 结题报告+源代码
- MySQL-函数处理
- 挂载iso镜像
- Android M 设置流程简要分析
- DBUTtils的介绍
- 产品新人必读,老鸟也要多翻几遍的互联网圣经——《启示录》
- linux 中的用户和用户组管理一些命令
- notify和notifyAll区别
- Java 加解密技术系列之 SHA