1.题目描述
515. Find Largest Value in Each Tree Row
Medium
41337
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]
2.解题思路
BFS遍历每一层,比较每一层中最大的存入vector
3.代码
/**
* 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 largestValues(TreeNode* root) {
vector V;
if (root==NULL) return V;
queue Q;
Q.push(root);
while (!Q.empty()) {
int n=Q.size();//下面用到,用于判断是否是同一层
int temp = -2147483648;
for (int i=0; ileft) Q.push(Q.front()->left);
if (Q.front()->right) Q.push(Q.front()->right);
temp = max(temp, Q.front()->val);
Q.pop();
}
V.push_back(temp);
}
return V;
}
};