Code & Func
2019-12-18

第42天。

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

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

1
vector<int> largestValues(TreeNode* root) {
2
vector<int> res;
3
if (root == nullptr) return res;
4
queue<TreeNode *> q;
5
q.push(root);
6
7
while(!q.empty()) {
8
int max_v = INT_MIN;
9
for(int i = 0, size = q.size(); i < size; i++) {
10
root = q.front(); q.pop();
11
max_v = max(max_v, root->val);
12
if (root->left) q.push(root->left);
13
if (root->right) q.push(root->right);
14
}
15
res.push_back(max_v);
4 collapsed lines
16
}
17
18
return res;
19
}
上一条动态