2583. 二叉树中的第 K 大层和
思路:方法一,深度优先搜索dfs。
/**
* 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<long long> v;
void dfs(TreeNode * root,int u){
if(root==nullptr) return ;
v[u]+=root->val;
dfs(root->left,u+1);
dfs(root->right,u+1);
}
long long kthLargestLevelSum(TreeNode* root, int k) {
v=vector<long long>(100010,0);
dfs(root,1);
sort(v.begin(),v.end(),greater<long long>());
if(v[k-1]==0) return -1;
return v[k-1];
}
};
思路:方法二,广度优先搜索bfs
/**
* 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:
long long kthLargestLevelSum(TreeNode* root, int k) {
vector<long long> v=vector<long long>(100010,0);
queue<pair<TreeNode *,int>> qu;
qu.push({root,1});
while(qu.size()){
auto tmp=qu.front();
qu.pop();
if(tmp.first==nullptr) continue;
v[tmp.second]+=tmp.first->val;
qu.push({tmp.first->left,tmp.second+1});
qu.push({tmp.first->right,tmp.second+1});
}
sort(v.begin(),v.end(),greater<long long>());
return v[k-1]==0 ? -1:v[k-1];
}
};