您需要在二叉树的每一行中找到最大的值。
示例:
输入:
1
/ \
3 2
/ \ \
5 3 9
输出: [1, 3, 9]
class Solution {
public:
//DFS
vector<int> largestValues(TreeNode* root) {
vector<int> res;
queue<TreeNode*> que;
if(root) que.push(root);
while(!que.empty()) {
int length = que.size();
int maxValue = INT_MIN;
for(int i = 0; i < length; ++i) {
TreeNode* tmp = que.front();
que.pop();
maxValue = max(maxValue, tmp->val);
if(tmp->left) que.push(tmp->left);
if(tmp->right) que.push(tmp->right);
}
res.push_back(maxValue);
}
return res;
}
};
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int> res;
bfs(0, root, res);
return res;
}
void bfs(int level, TreeNode* root, vector<int>& res) {
if(root) {
if(level >= res.size()) res.push_back(root->val);
else res[level] = max(res[level], root->val);
res[level] = max(res[level], root->val);
bfs(level + 1, root->left, res);
bfs(level + 1, root->right, res);
}
}
};