树的基本操作,静态法

来源:互联网 发布:怎么办我爱你网络歌手 编辑:程序博客网 时间:2024/05/21 14:06

树的基本操作

1.定义

lchid和rchild存放的是在tree的序号,不是data值

struct node{int data;int lchild;int rchild;}tree[MAX];

2.新建节点

-1表示没有该节点,代替NULL

int index=0;int newNode(){    tree[index].lchid=-1;    tree[index].rchid=-1;    return index++;}

3.查找某节点,并修改其值

//root为根节点的下标void search(int root,int x,int newdata){if(root==-1){return;}if(tree[root].data==x){tree[root].data=newdata;}search(tree[root].lchild,x,newdata);search(tree[root].rchild,x,newdata);}

4.插入和建立

//root为根节点的下标void insert(int root,int x){if(root==-1){root=newNode();tree[root].data=x;return;}if(插在左子树的性质){insert(tree[root].lchild,x)}else{insert(tree[root].rchild,x);}}//建立二叉树,其值存在a[]中int create(int n,int a[]){    int root=newNode();    tree[root].data=a[0];    for(int i=1;i<n;i++){        insert(root,data[i]);    }    return root;}

5.遍历

//先序void pre(int root){if(root==-1){return;}//访问该节点visit(tree[root].data);pre(tree[root].lchild);pre(tree[root].rchild);}//中序void in(int root){if(root==-1){return;}in(tree[root].lchild);//访问该节点visit(tree[root].data);in(tree[root].rchild);}//后序void post(int root){if(root==-1){return;}post(tree[root].lchild);post(tree[root].rchild);//访问该节点visit(tree[root].data);}//层次void dfs(int root){queue <int> q;q.push(root);while(!q.empty()){int now=q.front();q.pop();//访问该节点visit(tree[root].data);if(tree[now].lchild!=-1){q.push(tree[now].lchild);}if(tree[now].rchild!=-1){q.push(tree[now].rchild);}}}




0 0