题目链接【link】
给定一棵二叉树的根节点 root ,请找出该二叉树中每一层的最大值。
示例1:
输入: root = [1,3,2,5,3,null,9]
输出: [1,3,9]
解释:
1
/
3 2
/ \ \
5 3 9
class Solution {
public:
void dfs(vector<int>&ans,TreeNode*root,int curHeight){
if(curHeight==ans.size()){
ans.emplace_back(root->val);
}else{
ans[curHeight]=max(ans[curHeight],root->val);
}
if(root->left){
dfs(ans,root->left,curHeight+1);
}
if(root->right){
dfs(ans,root->right,curHeight+1);
}
}
vector<int> largestValues(TreeNode* root) {
vector<int>ans;
if(root!=NULL){
dfs(ans,root,0);
}
return ans;
}
};
BFS的方式:
一开始用的是BFS,但是因为结点类中没有height的参数,卡在了不知道如何存储结点height信息上,看了题解,题解的思路是利用了BFS的特性——即遍历完一层再执行下一层,这样就没有存储height的信息的压力.
但是时间和空间复杂度上都要比DFS高,不是最优解法
class Solution {
public:
vector<int> largestValues(TreeNode* root) {
vector<int>ans;
if(root!=NULL){
int len;
int max_value;
queue<TreeNode*>q;
q.push(root);
while(!q.empty()){
len=q.size();
TreeNode*top;
max_value=INT_MIN;
while(len--){
top=q.front();
q.pop();
if(top->left!=NULL){
q.push(top->left);
}
if(top->right!=NULL){
q.push(top->right);
}
if(top->val>max_value){
max_value=top->val;
}
}
ans.emplace_back(max_value);
}
}
return ans;
}
};