简体   繁体   中英

Sum of last N nodes in a binary search tree

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?

You can simply visit the tree in reverse order, that means starting from root and do three things:

  1. visit right branch
  2. visit self node, and accumulate sum if needed
  3. visit left branch

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM