来源:EPI
原帖:EPI 11.11. pg. 312.
题目:
Given the root of a BST and an integer k, design a function that finds the k largest elements in this BST. For example, if the input to your function is the BST in Figure 11.1 on Page 87 and k = 3, your function should return <53, 47, 43>.
代码:
原帖:EPI 11.11. pg. 312.
题目:
Given the root of a BST and an integer k, design a function that finds the k largest elements in this BST. For example, if the input to your function is the BST in Figure 11.1 on Page 87 and k = 3, your function should return <53, 47, 43>.
代码:
struct TreeNode {
int val;
TreeNode* left;
TreeNode* right;
TreeNode(int v) : val(v), left(NULL), right(NULL) {}
};
void find_k_largest_in_BST_helper(TreeNode* root, int k, vector<int> &k_elements) {
if (!root || k_element.size() == k) {
return;
}
// Perform reverse inorder traversal
if (root && k_elements.size() < k) {
find_k_largest_in_BST_helper(root->right, k, k_elements);
if (k_elements.size() < k) {
k_elements.push_back(root->val);
find_k_largest_in_BST_helper(root->left, k, k_elements);
}
}
}
vector<int> find_k_largest_in_BST(TreeNode* root, int k) {
vector<int> k_elements;
find_k_largest_in_BST_helper(root, k , k_elements);
return k_elements;
}
No comments:
Post a Comment