二叉树的建立

来源:互联网 发布:数据采集技术有哪些 编辑:程序博客网 时间:2024/06/07 08:08

一:利用字符"#"作为结点左右孩子不存在的标记,有以下俩种方法

<1>scanf逐个输入字符串的情况:

BtNode * CreateTree1(){BtNode *s = NULL;ElemType item;scanf("%c",&item);if(item != '#'){s = Buynode();s->data = item;s->leftchild = CreateTree1();s->rightchild = CreateTree1();}return s;}
<2>字符串中包含字符"#"的情况:

BtNode * CreateTree2(char *&str){BtNode *s = NULL;if(str != NULL && *str != '#'){s = Buynode();s->data = *str;s->leftchild = CreateTree2(++str);s->rightchild = CreateTree2(++str);}return s;}
二:根据前序遍历和中序遍历建立二叉树

例://char *ps = “ABCDEFGH”; char *is = “CBEDFAGH”;

int FindIs(char *is,int n,ElemType x)//用来找到中序遍历中根结点的位置{for(int i = 0;i<n;++i){if(is[i] == x)return i;}return -1;}//char *ps = “ABCDEFGH”; char *is = “CBEDFAGH”;BtNode * Create(char *ps,char *is,int n){BtNode *s = NULL;if(n > 0){s = Buynode();s->data = ps[0];//前序遍历的第一个值为二叉树的根结点int pos = FindIs(is,n,ps[0]);if(pos == -1) exit(1);s->leftchild = Create(ps+1,is,pos);//将中序遍历后的根结点左右俩边分为左右子树s->rightchild = Create(ps+pos+1,is+pos+1,n-pos-1);}return s;}
三:根据中序遍历和后序遍历建立二叉树
int FindIs(char *is,int n,ElemType x)//找到根结点在中序遍历的位置{for(int i = 0;i<n;++i){if(is[i] == x)return i;}return -1;}BtNode * Create2(char *is,char *ls,int n){BtNode *s = NULL;if(n > 0)           //{int pos = FindIs(is,n,ls[n-1]);//切入点:后序遍历最后一个结点为二叉树的根结点if(pos == -1) exit(1);s = Buynode();s->data = ls[n-1];s->leftchild = Create2(is,ls,pos);s->rightchild = Create2(is+pos+1,ls+pos,n-pos-1);}return s;}BtNode * CreateIL(char *is,char *ls,int n){if(is == NULL || ls == NULL || n < 1)return NULL;elsereturn Create2(is,ls,n);}




原创粉丝点击