Найти и удалить медиану в двоичном дереве поиска C

Я работаю над структурами данных в C, и мне нужно найти медианное значение значений в BST и удалить медианное значение, а затем продемонстрировать новый BST, но мне это не удалось. Я действительно не знаю, в чем я ошибаюсь. Пожалуйста, помогите меня об этом. Мне также нужно найти значение, наиболее близкое к среднему, и удалить его.

#include<stdio.h>
#include<stdlib.h>

struct Node
{
int key;
struct Node* left, *right;
};

//Function to create new BST NODE
struct Node *newNode (int item)
{
struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
//Function to perform INORDER traversal operation
void inorder(struct Node *root)
{
if (root!=NULL)
{
inorder(root->left);
printf("%d\n",root->key);
inorder (root->right);
}
} 
//Function to insert new node with given key in BST
struct Node* insert (struct Node* node, int key)
{
//if tree is empty
if (node==NULL) return newNode(key);
//else, recur down the tree
if (key< node->key)
node->left  = insert(node->left,key);
else if (key > node->key)
node->right  = insert(node->right,key);
//Return the (unchanged) node pointer
return node;    
}


//Given a non-empty BST ,return node with minimum key value found in that          tree. Whole tree not really searched
struct Node * minValueNode(struct Node* node)
{
struct Node* current =node;
//loop down to find the left-most leaf
while (current->left !=NULL)
    current = current->left;
return current;
}
//Given the BST and key, function to deleted the key to return new root
struct Node* deleteNode(struct Node* root, int key)
{
if (root == NULL) return root;
if (key<root->key)
    root->left = deleteNode(root->left,key);
else if (key> root->key)
    root->right = deleteNode(root->right, key);
else
{
    //node with one or no child
    if (root->left == NULL)
    {
        struct Node *temp = root->right;
        free(root);
        return temp;
    }
 else if (root->right == NULL)
 {
    struct Node *temp = root->left;
    free(root);
    return temp;
}
//node with two children
struct Node* temp = minValueNode(root->right);
//copy the inorder successor to this node
root->key = temp->key;
//delete the inorder successor
root->right = deleteNode(root->right, temp->key);
}
return root;
}
//Function to count nodes in a BST using Morris Inorder traversal
int counNodes(struct Node *root)
{
struct Node *current, *pre;
int count =0;
if (root == NULL)
    return count;
current = root;
while(current!=NULL)
{
    if (current->left == NULL)
    {
        count++;
        current = current->right;;
    }
    else
    {
        pre = current->left;
        while(pre->right !=NULL && pre->right !=current) 
        pre=pre->right;
        if (pre->right == NULL)
        {
            pre->right = current;
            current= current->left;
        }
        else
        {
            pre->right = NULL;
            count++;
            current = current->right;
        }
    }
}
return count;
} 
/*FUNCTION TO FIND MEDIAN */
int FINDM(struct Node *root)
{
if (root == NULL)
    return 0;
    int count = counNodes(root);
    int currCount=0;
    struct Node *current = root, *pre, *prev;
    while(current !=NULL)
    {
        if (current->left == NULL)
        {
            currCount++;
            if (count%2!=0 && currCount ==(count+1)/2)
                return (prev->key);
                //EVEN NUMBERS
                else if (count%2==0 && currCount==(count/2)+1)
                    return (prev->key + current->key)/2;
                    prev = current;
                    current = current->right;
                }
                else
                {
                    pre=current->left;
                    while(pre->right !=NULL && pre->right !=current)
                    pre= pre->right;
                    if (pre->right = NULL)
                    {
                        pre->right = current;
                        current = current->left;
                    }
                    else
                    {
                        pre->right = NULL;
                        prev = pre;
                        currCount++;
                        if (count%2!=0 && currCount == (count+1)/2)
                            return (current->key);
    else if (count%2==0 && currCount ==  (count/2)+1)
                                return (prev->key+current->key)/2;
                                prev = current;
                                current = current->right;
                            }
                        }
                    }
                }

  //Driver Program to test functions above
int main()
{
// values are 28,90,0,32,56,78,212,34,62
struct Node *root =NULL;

root=insert(root,65);
insert(root, 28);
insert(root, 90);
insert(root,0);
insert(root, 32);
insert(root,56);
insert(root, 78);
insert(root,212);
insert(root,34);
insert(root,62);

printf("InOrder Traversal of Tree\n");
inorder(root);

printf("\nDelete 65!\n");
root=deleteNode(root,65);
printf("Modified Tree\n");
inorder(root);

printf("\nMEDIAN ");
FINDM(root);
return 0;
}

Ваше решение найдет медиану за время O (n). Нетрудно найти k-е по величине число в BST (что, конечно же, позволяет вам найти и медиану) за время O (log n), если вы сделаете его деревом статистики порядка. Поддержка статистики заказов не делает другие операции с деревом асимптотически медленнее.

Gene 02.05.2018 02:46

Возможный дубликат Найти медиану в двоичном дереве поиска

MFisherKDX 02.05.2018 02:47
Стоит ли изучать PHP в 2023-2024 годах?
Стоит ли изучать PHP в 2023-2024 годах?
Привет всем, сегодня я хочу высказать свои соображения по поводу вопроса, который я уже много раз получал в своем сообществе: "Стоит ли изучать PHP в...
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Приемы CSS-макетирования - floats и Flexbox
Приемы CSS-макетирования - floats и Flexbox
Здравствуйте, друзья-студенты! Готовы совершенствовать свои навыки веб-дизайна? Сегодня в нашем путешествии мы рассмотрим приемы CSS-верстки - в...
Тестирование функциональных ngrx-эффектов в Angular 16 с помощью Jest
В системе управления состояниями ngrx, совместимой с Angular 16, появились функциональные эффекты. Это здорово и делает код определенно легче для...
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Пользовательский скаляр GraphQL
Пользовательский скаляр GraphQL
Листовые узлы системы типов GraphQL называются скалярами. Достигнув скалярного типа, невозможно спуститься дальше по иерархии типов. Скалярный тип...
1
2
134
1

Ответы 1

У вас уже есть рабочая функция counNodes(), которая обходит узлы по порядку для подсчета количества узлов. Что, если вы используете этот точный код в новой функции, которая находит N-й узел в дереве:

struct Node *findNth(struct Node* root, int nth) {
    struct Node *current, *pre;
    int count = 0;
    if (root == NULL)
        return count;
    current = root;
    while (current != NULL)
    {
        if (current->left == NULL)
        {
            count++;
            if (count == nth) {
                return current;
            } else {
                current = current->right;;
            }
        } else
        {
            pre = current->left;
            while (pre->right != NULL && pre->right != current)
                pre = pre->right;
            if (pre->right == NULL)
            {
                pre->right = current;
                current = current->left;
            } else
            {
                pre->right = NULL;
                count++;
                if (count == nth) {
                    return current;
                } else {
                    current = current->right;
                }
            }
        }
    }

    printf("Could not find nth(%d)\n", nth);
    exit(1);
}


int FINDM(struct Node *root)
{
    if (root == NULL)
        return 0;
    int count = counNodes(root);

    struct Node *n = findNth(root, (count + 1) / 2);

    return n->key;
}

Другие вопросы по теме