You need to find the largest value in each row of a binary tree.
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Example:
Input:
1
/ \
3 2
/ \ \
5 3 9
Output: [1, 3, 9]
BFS+维护一个每行的长度+维护一个每行的max变量,每行遍历完之后把max压到res中。
/**
* 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;
q.push(root);
vector<int> res;
int length=1;
while(!q.empty()){
int maxs=INT_MIN;
for(int i=0; i<length; ++i){
TreeNode* tmp=q.front();
maxs=max(maxs, tmp->val);
if(tmp->left) q.push(tmp->left);
if(tmp->right) q.push(tmp->right);
q.pop();
}
res.push_back(maxs);
length=q.size();
}
return res;
}
};
其实这种题都有两种方法,BFS和DFS都是可以的。
一开始想了一个DFS先找到树的深度,然后按深度给res分配长度,后来想想其实多加一个判断条件就可以不用找深度了。
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
if(!root) return {};
vector<int> res;
dfs(res, root, 0);
return res;
}
void dfs(vector<int>& res, TreeNode* root, int depth){
if(!root) return ;
if(depth >= res.size()) res.push_back(root->val);
else if(root->val > res[depth]) res[depth] = root->val;
dfs(res, root->left, depth + 1);
dfs(res, root->right, depth + 1);
}
};