簡體   English   中英

二叉搜索樹中最后 N 個節點的總和

[英]Sum of last N nodes in a binary search tree

我想寫一個 function 得到一個數 N 和一個二叉搜索樹,那么 function 需要對樹的最后 N 個節點的值求和。 節點的值從高到低。 我不能使用輔助功能或 static 變量。

例子

例如,如果 function 獲得該二叉搜索樹並且 N 的值為 3,則 output 將為:7+6+5。 如果 N 為 4,則為:7+6+5+3。

對算法有什么想法嗎?

您可以簡單地以相反的順序訪問樹,這意味着從根開始並做三件事:

  1. 訪問右分支
  2. 訪問自身節點,並在需要時累加總和
  3. 訪問左分支

並在 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;
}

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