📜  二叉查找树(BST)中给定范围内所有节点的中位数

📅  最后修改于: 2021-05-24 21:39:28             🧑  作者: Mango

给定一个由N个节点以及两个节点AB组成的二叉搜索树(BST),任务是查找给定BST中所有值位于[A,B]范围内的所有节点的中值。

例子:

方法:可以通过对给定树执行任何树遍历并存储范围[A,B]内的所有节点,并找到所有存储元素的中位数来解决给定问题。请按照以下步骤解决问题:

  • 初始化一个向量,比如说V ,该向量存储位于[A,B]范围内的树的所有值。
  • 执行给定树的有序遍历,如果任何节点的值都在[A,B]范围内,则将该值插入向量V中
  • 完成上述步骤后,打印存储在向量V中的所有元素的中值。

下面是上述方法的实现:

C++
// C++ program for the above approach
  
#include 
using namespace std;
  
// Tree Node structure
struct Node {
    struct Node *left, *right;
    int key;
};
  
// Function to create a new BST node
Node* newNode(int key)
{
    Node* temp = new Node;
    temp->key = key;
    temp->left = temp->right = NULL;
    return temp;
}
  
// Function to insert a new node with
// given key in BST
Node* insertNode(Node* node, int key)
{
    // If the tree is empty,
    // return a new node
    if (node == NULL)
        return newNode(key);
  
    // Otherwise, recur down the tree
    if (key < node->key)
        node->left = insertNode(
            node->left, key);
  
    else if (key > node->key)
        node->right = insertNode(
            node->right, key);
  
    // Return the node pointer
    return node;
}
  
// Function to find all the nodes that
// lies over the range [node1, node2]
void getIntermediateNodes(
    Node* root, vector& interNodes,
    int node1, int node2)
{
    // If the tree is empty, return
    if (root == NULL)
        return;
  
    // Traverse for the left subtree
    getIntermediateNodes(root->left,
                         interNodes,
                         node1, node2);
  
    // If a second node is found,
    // then update the flag as false
    if (root->key <= node2
        and root->key >= node1) {
        interNodes.push_back(root->key);
    }
  
    // Traverse the right subtree
    getIntermediateNodes(root->right,
                         interNodes,
                         node1, node2);
}
  
// Function to find the median of all
// the values in the given BST that
// lies over the range [node1, node2]
float findMedian(Node* root, int node1,
                 int node2)
{
    // Stores all the nodes in
    // the range [node1, node2]
    vector interNodes;
  
    getIntermediateNodes(root, interNodes,
                         node1, node2);
  
    // Store the size of the array
    int nSize = interNodes.size();
  
    // Print the median of array
    // based on the size of array
    return (nSize % 2 == 1)
               ? (float)interNodes[nSize / 2]
               : (float)(interNodes[(nSize - 1) / 2]
                         + interNodes[nSize / 2])
                     / 2;
}
  
// Driver Code
int main()
{
    // Given BST
    struct Node* root = NULL;
    root = insertNode(root, 8);
    insertNode(root, 3);
    insertNode(root, 1);
    insertNode(root, 6);
    insertNode(root, 4);
    insertNode(root, 11);
    insertNode(root, 15);
  
    cout << findMedian(root, 3, 11);
  
    return 0;
}


输出:
6

时间复杂度: O(N)
辅助空间: O(N)