程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> c++實現二叉搜索樹

c++實現二叉搜索樹

編輯:C++入門知識

自己實現了一下二叉搜索樹的數據結構,記錄一下:

#include 

using namespace std;

struct TreeNode{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int value) { val=value; left=NULL; right=NULL; }
};


class SearchTree{

public:
    SearchTree();
    ~SearchTree();
    void Destory(TreeNode *);
    void Insertnode(int);
    void Preorder(TreeNode *);
    void Inorder(TreeNode *);
    void Postorder(TreeNode *);
    void Predisplay();
    void Indisplay();
    void Postdisplay();
private:
    TreeNode *root;

};

SearchTree::SearchTree()
{
    root=NULL;
}

SearchTree::~SearchTree()
{
    cout<<"析構二叉搜索樹:"<left);
        Destory(node->right);
        cout<val<<" ";
        delete node;
    }
}

void SearchTree::Insertnode(int value)
{
    if(root==NULL)
        root=new TreeNode(value);
    else
    {
        TreeNode *p,*pre;
        pre=p=root;
        while(p)
        {
            if(p->val==value)
                return;
            else if(p->val>value)
            {
                pre=p;
                p=p->left;
            }
            else
            {
                pre=p;
                p=p->right;
            }

        }
        p=new TreeNode(value);
        if(pre->val>value)
            pre->left=p;
        else
            pre->right=p;
    }
}


void SearchTree::Predisplay()
{
    Preorder(root);
}

void SearchTree::Preorder(TreeNode *root)
{
    if(root)
    {
        cout<val<<" ";
        Preorder(root->left);
        Preorder(root->right);
    }
}

void SearchTree::Indisplay()
{
    Inorder(root);
}

void SearchTree::Inorder(TreeNode *root)
{
    if(root)
    {
        Inorder(root->left);
        cout<val<<" ";
        Inorder(root->right);
    }
}

void SearchTree::Postdisplay()
{
    Postorder(root);
}

void SearchTree::Postorder(TreeNode *root)
{
    if(root)
    {
        Postorder(root->left);
        Postorder(root->right);
        cout<val<<" ";
    }
}

int main()
{
    SearchTree t;
    int a[]={7,4,2,3,15,35,6,45,55,20,1,14};
    int n=sizeof(a)/sizeof(a[0]);
    cout<<"構造二叉搜索樹:"<

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved