[笔记]: 二叉排序树

来源:互联网 发布:淘宝账号存在安全问题 编辑:程序博客网 时间:2024/06/12 07:15

二叉排序树:
二叉树中每个数都有 左结点小于根结点小于右结点
二叉排序树的中序遍历就是结点的data从小到大排序
建树过程:
对于每个结点 从根结点出发
如果大于结点就往右走
小于就往左走
如走到一个结点为空 则将此结点建入树

/*    如输入 31524    树为            3        1     5         2  4     这样是一棵二叉排序树     中序遍历则就是1 2 3 4 5 */#include<iostream>#include<cstdio>#include<cstdlib>#include<cstring>#include<cmath>#include<algorithm>using namespace std;struct node{    int data;    int left;    int right;    int bh;//编号 }tree[1000];void insert(int x,int sz){//data值和编号     int u=1,t;    while(1){        if(tree[u].data==0){//根结点             tree[u].data=x;            tree[u].bh=sz;            return ;        }        else if(x<tree[u].data){//左             if(tree[u].left){                u=tree[u].left;            }            else if(!tree[u].left){                t=0;                break;            }        }        else if(x>tree[u].data){//右             if(tree[u].right){                u=tree[u].right;            }            else if(!tree[u].right){                t=1;                break;            }        }    }    if(!t){        tree[u].left=sz;        tree[sz].bh=sz;        tree[sz].data=x;    }    else if(t){        tree[u].right=sz;        tree[sz].bh=sz;        tree[sz].data=x;    }}void dfs(int k){//中序遍历     if(tree[k].left){//左         dfs(tree[k].left);    }     cout<<tree[k].data<<" ";    if(tree[k].right){//右         dfs(tree[k].right);    } }int main(){    int n;    scanf("%d",&n);    for(int i=1;i<=n;i++)    {        int x;        scanf("%d",&x);        insert(x,i);    }    dfs(1);    return 0;}