思路:
简单题,遍历树,和对应的层数中的最大值比较就行了,具体看代码
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
vector <int> an;
int cnt = -1;
vector<int> largestValues(TreeNode* root) {
if(root != nullptr)
bianli(root, 0);
return an;
}
void bianli(TreeNode* node, int level){
while(level > cnt){
an.push_back(-1 * pow(2,31));
cnt++;
}
an[level] = max(an[level], node->val);
if(node->left != nullptr){
bianli(node->left, level+1);
}
if(node->right != nullptr){
bianli(node->right, level+1);
}
}
};