lc 515 Find Largest Value in Each Tree Row
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]
BFS Accepted
相比之前的几道用到BFS算法的题目,这题相对来说会繁琐一些,需要用变量记录每一个节点所在的层数l,当前比较大小的层数m,重要的是厘清思路,其实也挺简单的,就是容易脑子搭线,陷入僵局。
/**
* 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<int> largestValues(TreeNode* root) {
if (!root) return {};
queue<TreeNode*> q;
queue<int> level;
vector<int> ans;
q.push(root);
level.push(0);
int m = -1;
while(!q.empty()) {
TreeNode* temp = q.front();
q.pop();
int l = level.front();
level.pop();
if (temp->left) {
q.push(temp->left);
level.push(l+1);
}
if (temp->right) {
q.push(temp->right);
level.push(l+1);
}
if (l > m) {
m = l;
ans.push_back(temp->val);
} else {
ans[l] = max(ans[l], temp->val);
}
}
return ans;
}
};