LeetCode 515. Find Largest Value in Each Tree Row
来源:互联网 发布:携程程序员怒删数据库 编辑:程序博客网 时间:2024/05/17 23:37
题目
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。
可以很容易想到用层序遍历来实现,遍历每一层保存每一层的最大值。需要用一个值来保存当前层的节点个数,然后将子节点放入一个队列中,从而实现每一层的遍历。
是用一个容器vec来做辅助队列,当vec大小为整个树所有节点数时,说明遍历结束。用一个数cur来辅助这一过程,每遍历一个节点cur加一,并将该节点的左右子节点压入vec中,遍历结束时,树中全部节点都在vec中,而cur为全部节点数。
在遍历每一层时,用i来表示每一层的节点数,用max表示这一层的最大值,访问每个节点时更新max,这一层访问结束后,将max存入结果容器res中。
需要注意的时两层循环之间的关系,以及各自的结束条件。
代码
/** * 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 == NULL) return res; vector<TreeNode*> vec; //辅助队列用于遍历全部节点 vec.push_back(root); int cur = 0; int i = 0; while(cur<vec.size()) { i = vec.size(); //当前层的节点个数 int max = vec[cur]->val; //用来保存当前层最大值 while(cur<i) { if(max < vec[cur]->val) max = vec[cur]->val; if(vec[cur]->left != NULL) vec.push_back(vec[cur]->left); if(vec[cur]->right != NULL) vec.push_back(vec[cur]->right); cur++; } res.push_back(max); } return res; }};
阅读全文
0 0
- 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 (C++)
- 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
- Java后端WebSocket的Tomcat实现
- MIRO业务类型
- 单片机时钟程序(7)key.h
- 浙大PAT甲级-1006
- Android热点相关功能开发
- LeetCode 515. Find Largest Value in Each Tree Row
- Maven 本地仓库明明有jar包,但是pom文件还是报错解决办法
- 23-树的层次遍历
- IDC机房服务器
- jmeter个人学习之路--jmeter结果分析
- NXP 蓝牙QN902X 协议profile的理解
- HashMap的tableSizeFor算法理解
- 【计组】--数值的机器运算(1): 加法器
- 自定义监听回调