建树与输出

#include<iostream>  
using namespace std;  
  
typedef struct node{
    node *le;
    node *re;
    char data;
}BiTreeNode,*BiTree;  
  
void createBiTree(BiTree &T){
    char c;
    cin>>c;
    if(c=='#')
        T=NULL;
    else{
        T=new BiTreeNode;
        T->data=c;
        createBiTree(T->le);
        createBiTree(T->re);
    }
}  
void printTree(BiTree &T){
    if(T){
        
        printTree(T->le);
        printf("%c ",T->data);
        printTree(T->re);
    }
}
  
int main()  
{  
    BiTree T;  
    createBiTree(T);  
    printTree(T);
    return 0;  
}

树的遍历

已知后序遍历和中序遍历求层序遍历

#include <cstdio>  
#include <cstdlib>  
#include <queue>  
  
using namespace std;  
  
const int maxx = 32;  
  
typedef struct Tree{  
    Tree *le;  
    Tree *ri;  
    int data;  
}Tree;  
  
Tree *root;  
  
int pos[maxx],in[maxx];  

void printLevelOrder(Tree *root){  
    queue<Tree *> que;  
    Tree *tr = NULL;  
    que.push(root);  
    bool flg = true;  
    while(!que.empty()){  
        tr = (Tree *)que.front();  
        que.pop();  
        if(tr==NULL)continue;  
        if(flg){  
            printf("%d",tr->data);  
            flg = false;  
        }else{  
            printf(" %d",tr->data);  
        }  
        que.push(tr->le);  
        que.push(tr->ri);  
    }  
    printf("\n");  
}  
Tree *buildTree(int pl,int pr,int il,int ir){  
    if(pl>pr)return NULL;  
    int p = il;  
    while(in[p]!=pos[pr])++p;  
  
    Tree *tree = (Tree *)malloc(sizeof(Tree));  
    tree->data = pos[pr];  
    tree->le = buildTree(pl,pr-ir+p-1,il,p-1);  
    tree->ri = buildTree(pr-ir+p,pr-1,p+1,ir);  
      
    return tree;  
}  
  
int main(){  
    int n,i;  
    Tree *root;  
  
    scanf("%d",&n);  
    for(i=0;i<n;++i){  
        scanf("%d",&pos[i]);  
    }  
    for(i=0;i<n;++i){  
        scanf("%d",&in[i]);  
    }  
    root=buildTree(0,n-1,0,n-1);  
    printLevelOrder(root);  
    return 0;  
}  
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 给定一个前序和中序变量的结果,写一个算法重建这棵树:前序: a b d c e f中序: d b a e c f...
    HangChen阅读 3,550评论 0 3
  • 编译环境:python v3.5.0, mac osx 10.11.4 前述内容: 线性表 队列 堆栈 线性结构...
    掷骰子的求阅读 7,387评论 1 7
  • 数据结构和算法--二叉树的实现 几种二叉树 1、二叉树 和普通的树相比,二叉树有如下特点: 每个结点最多只有两棵子...
    sunhaiyu阅读 11,587评论 0 14
  • 1.树(Tree): 树是 n(n>=0) 个结点的有限集。当 n=0 时称为空树。在任意一颗非空树中:有且仅有一...
    ql2012jz阅读 4,765评论 0 3
  • 我是一个喜爱写字的博主,刚开始玩简书。我要在这里“热”起来。 我是简书上的“愚先”,微博上的“写字好看的人”,有个...
    愚先阅读 4,716评论 2 1

友情链接更多精彩内容