Description
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]
Explain
这题题意一眼就知道要干嘛,言简意赅。就是要找树的每一层的最大值。这里在leetcode的分类是DFS。然后我觉得这题用BFS来做更好做一点,也更好理解一点。我们只要遍历每一层的节点,然后比较得出最大值,然后插入vector即可。下面上代码
Code
/**
* 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) {
vector<int> res;
if (!root) return res;
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int len = q.size();
int max = INT_MIN;
for (int i = 0; i < len; i++) {
TreeNode* cur = q.front();
q.pop();
if (cur->val > max) max = cur->val;
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
res.push_back(max);
}
return res;
}
};