515. Find Largest Value in Each Tree Row
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]
代码如下:
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
if(root == NULL) return {};
vector<int> mac;
queue<TreeNode*> q;
queue<int> level;
q.push(root);
level.push(0);
int m = -1;
while (q.size()) {
TreeNode *r = q.front();
q.pop();
int l = level.front();
level.pop();
if(r->left) {
q.push(r->left);
level.push(l+1);
}
if(r->right){
q.push(r->right);
level.push(l+1);
}
if(l > m){
m = l;
mac.push_back(r->val);
} else {
mac[l] = std::max(mac[l], r->val);
}
}
return mac;
}
};
解题思路:
- 本题采用了BFS算法,利用队列q,level 以及向量 mac;
- q用来存放遍历到的结点,level记录当前结点出于哪一层,mac则存放每一层的最大值;
- 当两个结点处于不同层时,直接压入队列q;若出于同一层,则与原有值进行对比,把较大的那一个存入该位置。