简体   繁体   English

二叉搜索树中最后 N 个节点的总和

[英]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.我想写一个 function 得到一个数 N 和一个二叉搜索树,那么 function 需要对树的最后 N 个节点的值求和。 from higher to lower value of the nodes.节点的值从高到低。 I cant use auxiliar functions or static variable.我不能使用辅助功能或 static 变量。

例子

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.例如,如果 function 获得该二叉搜索树并且 N 的值为 3,则 output 将为:7+6+5。 And if N its 4 it would be: 7+6+5+3.如果 N 为 4,则为: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.并在 k 项累积时停止迭代。

#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: output 是:

k=1 sum=7
k=3 sum=18
k=4 sum=22

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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