二叉树的建立
来源:互联网 发布:数据采集技术有哪些 编辑:程序博客网 时间: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);}
阅读全文
1 0
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 【二叉树的建立】
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 二叉树的建立
- 电视机也能应答如流?暴风TV开启AI 2.0时代
- 前方高能,相拼相爱!2017年“达能少年世界杯”落幕
- 踢进了世界杯还惊动了齐达内,这样的中国男足你见过没?
- Django基础,Day7
- Django-REST之1:serializers序列器-翻译及自己的学习笔记(更新完善中...)
- 二叉树的建立
- Mac下 常用程序 无限试用方法
- A*寻路极限优化
- spring boot API 完整版
- luogu3379 最近公共祖先(LCA) tarjan 倍增
- [POJ3259]Wormholes(负环)
- Django基础,Day8
- HDU 6113 度度熊的01世界(dfs)
- AI时代职场人何去何从?五大葩王带你深入解读