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來做更好做一點星虹,也更好理解一點。我們只要遍歷每一層的節(jié)點浊洞,然后比較得出最大值把曼,然后插入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;
}
};