Find Largest Value in Each Tree Row

第42天。

今天的题目是Find Largest Value in Each Tree Row:

水题,用队列做树的层次遍历即可:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
vector<int> largestValues(TreeNode* root) {
vector<int> res;
if (root == nullptr) return res;
queue<TreeNode *> q;
q.push(root);

while(!q.empty()) {
int max_v = INT_MIN;
for(int i = 0, size = q.size(); i < size; i++) {
root = q.front(); q.pop();
max_v = max(max_v, root->val);
if (root->left) q.push(root->left);
if (root->right) q.push(root->right);
}
res.push_back(max_v);
}

return res;
}