515. Find Largest Value in Each Tree Row | Breadth-first Search
来源:互联网 发布:php 中class exists 编辑:程序博客网 时间:2024/06/08 05:35
Description
You need to find the largest value in each row of a binary tree.
Example:
Difficluty:Medium
Thinking
典型的广度优先搜索算法题。用BFS遍历树,再用一个数组记录每一行的最大值即可。for循环遍历一层的条件是 i < size,size是下层子节点push进队列前的queue.size();
Solution
/** * 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) { if(!root) return {}; vector<int> maxv; queue<TreeNode*> q; q.push(root); while(!q.empty()){ int max = INT_MIN; int size = q.size(); for(int i = 0; i < size; i++){ TreeNode* temp = q.front(); q.pop(); if(max < temp->val) max = temp->val; if(temp->left) q.push(temp->left); if(temp->right) q.push(temp->right); } maxv.push_back(max); } return maxv; }};
阅读全文
0 0
- 515. Find Largest Value in Each Tree Row | Breadth-first Search
- Breadth-first Search -- Leetcode problem515. 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
- 515. Find Largest Value in Each Tree Row
- LeetCode OJ 515. Find Largest Value in Each Tree Row
- 515. Find Largest Value in Each Tree Row
- 515. Find Largest Value in Each Tree Row
- week3-NO.515. Find Largest Value in Each Tree Row
- LeetCode笔记:515. Find Largest Value in Each Tree Row
- 链表的简单实现
- 前端开发框架文档
- Shell使用总结(二)
- 软考新思维--2017年上半年信息系统项目管理师上午试题分析与答案(试题30-35题)
- 【unity优化】渲染批处理
- 515. Find Largest Value in Each Tree Row | Breadth-first Search
- 《软考下午题之数据库建模》
- linux中readl()和writel()函数
- Mac的bash_profile文件的进入和退出指令
- 如何访问虚拟机中的架设的Web服务器(解决方法)
- 一个进程为什么会默认打开三个标准输入输出
- Unity Shader学习-1.渲染流水线
- 欢迎使用CSDN-markdown编辑器
- 算法设计与结构基础作业第十六周