赞
踩
以字符串的形式定义一棵二叉树的先序序列,若字符是‘#’, 表示该二叉树是空树,否则该字符是相应结点的数据元素。读入相应先序序列,建立二叉树,然后按层次遍历该二叉树并输出结点数据。
字符串形式的先序序列(即结点的数据类型为单个字符)
按层次遍历二叉树的结果
在这里给出一组输入。例如:
ABDG##HI####CE#J##F##
在这里给出相应的输出。例如:
ABCDEFGHJI
-
- #include<iostream>
- #include<string>
- #include<queue>
- using namespace std;
-
- typedef struct TNode{
- char data;
- struct TNode *lchild,*rchild;
- }TNode,*pTNode;
-
- void creatTree(pTNode &root,string &T,int &start,int end){
- if(T[start]!='#'){
- root= new TNode;
- root->data = T[start];
- root->lchild = NULL;
- root->rchild = NULL;
- creatTree(root->lchild,T,++start,end);
- creatTree(root->rchild,T,++start,end);
- }
- }
- void leveltraversal(pTNode &root){
- queue <pTNode> q;
- pTNode p = root;
- q.push(p);
- while(!q.empty()){
- p = q.front();
- q.pop();
- cout<<p->data;
- if(p->lchild!=NULL){
- q.push(p->lchild);
- }
- if(p->rchild!=NULL){
- q.push(p->rchild);
- }
- }
- }
-
- int main(){
- string T;
-
- cin>>T;
- int st = 0;
- int &start = st;
-
- if(T[0]!='#'){
- pTNode root = new TNode;
- root->data = T[0];
- root->lchild = NULL;
- root->rchild = NULL;
- creatTree(root->lchild,T,++start,T.length());
- creatTree(root->rchild,T,++start,T.length());
- leveltraversal(root);
- }
-
-
-
-
- return 0;
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。