Reputation: 5
I want to write a function that obtains a number N and a binary search tree, then the function needs to sum the value of the last N nodes of the tree. from higher to lower value of the nodes. I cant use auxiliar functions or static variable.
For example, if the function obtains that binary search tree and the value of N its 3, then the output would be: 7+6+5. And if N its 4 it would be: 7+6+5+3.
Any ideas for an algorithm?
Upvotes: 0
Views: 603
Reputation: 764
You can simply visit the tree in reverse order, that means starting from root and do three things:
And stop iterating when k items are accumulated.
#include <iostream>
struct Node {
int value;
Node* left = nullptr;
Node* right = nullptr;
Node(int v) : value(v) {}
};
// Visit the tree in reverse order and get sum of top k items.
int sumK(Node* root, int& k) {
if (root == nullptr) return 0;
int sum = 0;
if (k > 0 && root->right) {
sum += sumK(root->right, k);
}
if (k > 0) {
sum += root->value;
k--;
}
if (k > 0 && root->left) {
sum += sumK(root->left, k);
}
return sum;
}
int main () {
// The following code hard coded a tree matches the picture in your question.
// I did not free the tree, so there will be memory leaking, but that is not relevant to this test.
Node* root = new Node(5);
root->right = new Node(6);
root->right->right = new Node(7);
root->left = new Node(3);
root->left->right = new Node(4);
root->left->left = new Node(2);
root->left->left->left = new Node(1);
// TODO: delete the tree after testing.
int k = 1;
std::cout << "k=" << k << " sum=" << sumK(root, k) << std::endl;
k = 3;
std::cout << "k=" << k << " sum=" << sumK(root, k) << std::endl;
k = 4;
std::cout << "k=" << k << " sum=" << sumK(root, k) << std::endl;
}
The output is:
k=1 sum=7
k=3 sum=18
k=4 sum=22
Upvotes: 3