如何在此代码中找到二叉搜索树的深度?

时间:2019-01-06 18:45:16

标签: c++ binary-search-tree

我正在分析此代码,并试图找出如何找到此二进制搜索树实现的最大深度。

#include<iostream>

using namespace std;

class BST
{
struct node
{
    int data;
    node* left;
    node* right;
};

node* root;

node* makeEmpty(node* t)
{
    if(t == NULL)
        return NULL;
    {
        makeEmpty(t->left);
        makeEmpty(t->right);
        delete t;
    }
    return NULL;
}

node* insert(int x, node* t)
{
    if(t == NULL)
    {
        t = new node;
        t->data = x;
        t->left = t->right = NULL;
    }
    else if(x < t->data)
        t->left = insert(x, t->left);
    else if(x > t->data)
        t->right = insert(x, t->right);
    return t;
}

node* findMin(node* t)
{
    if(t == NULL)
        return NULL;
    else if(t->left == NULL)
        return t;
    else
        return findMin(t->left);
}

node* findMax(node* t)
{
    if(t == NULL)
        return NULL;
    else if(t->right == NULL)
        return t;
    else
        return findMax(t->right);
}

node* remove(int x, node* t)
{
    node* temp;
    if(t == NULL)
        return NULL;
    else if(x < t->data)
        t->left = remove(x, t->left);
    else if(x > t->data)
        t->right = remove(x, t->right);
    else if(t->left && t->right)
    {
        temp = findMin(t->right);
        t->data = temp->data;
        t->right = remove(t->data, t->right);
    }
    else
    {
        temp = t;
        if(t->left == NULL)
            t = t->right;
        else if(t->right == NULL)
            t = t->left;
        delete temp;
    }

    return t;
}

void inorder(node* t)
{
    if(t == NULL)
        return;
    inorder(t->left);
    cout << t->data << " ";
    inorder(t->right);
}

node* find(node* t, int x)
{
    if(t == NULL)
        return NULL;
    else if(x < t->data)
        return find(t->left, x);
    else if(x > t->data)
        return find(t->right, x);
    else
        return t;
}

public:
BST()
{
    root = NULL;
}

~BST()
{
    root = makeEmpty(root);
}

void insert(int x)
{
    root = insert(x, root);
}

void remove(int x)
{
    root = remove(x, root);
}

void display()
{
    inorder(root);
    cout << endl;
}

void search(int x)
{
    root = find(root, x);
}
};

int main()
{
srand(time(NULL));

 BST t;

 for(int i=0; i<1000000; i++)
    {
        t.insert((rand()*rand())%10);
    }

t.display();
} 

有简单的方法吗? 我应该使用findMax函数还是不是正确的方向? 我为我的项目需要它,而时间用尽了一点,我们在课堂上没有得到太多的支持,所以我在这里尝试机会。

0 个答案:

没有答案