二叉排序树的建立

来源:互联网 发布:wps当前网络受限 编辑:程序博客网 时间:2024/06/06 02:31

首先二叉树排序树(Binary Sort Tree) 简称BST,又叫二叉查找树。具有以下性质:

  1. 若它的左子树不为空,则左子树上的所有结点的值均小于它的根结构的值
  2. 若它的右子树不为空,则右子树上的所有结点的值均大于它的根结构的值
  3. 它的左,右子树也分别为二叉排序树。

简单的概括起来就是:左<中<右
由此可知,二叉排序树的中序遍历一定是严格递增的。
代码:

#include<iostream>using namespace std;typedef struct node{    int data;    struct node *lc;    struct node *rc;}NODE;//向BST中插入新节点bool insert(NODE * &p,int n){    //空树时    if(p==NULL){        p = new NODE;        p->data = n;        p->lc = p->rc = NULL;        return true;    }    //BST中不能有相同的值    if(n==p->data){return false;}    //递归    if(n<p->data)        return insert(p->lc,n);    else        return insert(p->rc,n);}//建立BSTvoid buildBST(NODE * &p,int n,int a[]){    p = NULL;    for(int i=0;i<n;i++)        insert(p,a[i]);}/*前序遍历*/void inorder(NODE *t){    if(t){        cout<<t->data<<" ";        inorder(t->lc);        inorder(t->rc);    }}/*中序遍历*/void preorder(NODE *t){    if(t){        preorder(t->lc);        cout<<t->data<<" ";        preorder(t->rc);    }}int main(){    int a[7] = {2,3,1,5,7,6,4};    int n = sizeof(a)/sizeof(a[0]);    NODE *t;    buildBST(t,n,a);    inorder(t);    cout<<endl;    preorder(t);    cout<<endl;}

可知二叉树有,前,中,后和层次遍历。当我们知道,中序遍历,和其他三种中的一种时,就可以构造出原先的二叉树。之后的文章中会给出相应的代码