Find Largest Value in Each Tree Row(找出一棵树每一行的最大值)
来源:互联网 发布:批发源码 编辑:程序博客网 时间:2024/06/05 03:01
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]
找出树的每一行最大的值:
方法非常简单,用广度优先遍历
上述例子:首先将根节点存入一个队列q
对第一次循环,获得队列中节点个数c1(=1),每次从队列q中取出一个节点,比较该行最大值max1与该节点的值,用较大的值更新max1
同时将该节点的子节点存入队列中
这样当第一次循环,取完c1个节点时,队列中会个存在,前c1个节点所有子节点
如此第二次循环,获取队列中节点个数c2,正好等于第二层的节点数,同样的方法获得该层最大值
直至队列为空,代码如下:
public: vector<int> largestValues(TreeNode* root) { queue<TreeNode*> q; vector<int> v; if(root == NULL){ return v; } int c = 1; q.push(root); while(q.empty()==0){ int c = q.size(); int max = q.front()->val; for(int i = 0; i < c; ++i){ TreeNode *t = q.front(); q.pop(); if(max < t->val){ max = t->val; } if(t->left != NULL){ q.push(t->left); } if(t->right != NULL){ q.push(t->right); } } v.push_back(max); } return v; }
阅读全文
0 0
- Find Largest Value in Each Tree Row(找出一棵树每一行的最大值)
- LeetCode-515. Find Largest Value in Each Tree Row (JAVA)(二叉树每行的最大值)
- 【LeetCode515 Find Largest Value in Each Tree Row】二叉树每行的最大值
- 515. 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
- 515. Find Largest Value in Each Tree Row(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
- leetcode515: Find Largest Value in Each Tree Row
- centos7 安装 matplotlib和numpy
- The Suspects(POJ-1611)
- gps 简介---之一
- win10配置java环境变量,解决javac不是内部或外部命令等问题
- 图的遍历以及二叉树的遍历
- Find Largest Value in Each Tree Row(找出一棵树每一行的最大值)
- 【HDU1421】搬寝室
- 计蒜客 B kmp基础 kmp模板
- POJ 1273 Drainage Ditches 笔记
- 下个五年
- Solr--企业级搜索应用服务器
- OpenGL入门
- 基础4
- 实验1-ADS1.2的使用