属于二叉树——根据先序遍历和中序遍历建立二叉树

题目: 根据先序遍历和中序遍历建立二叉树的二叉链表 并输出后序序列

思路:

  1. 根据先序序列确定根节点
  2. 在中序序列中找到根节点,将中序序列分成两段,前半段为根节点的左子树的中序序列,后半段为右子树的中序序列
  3. 递归直到每颗子树只有一个结点。

示例:

    	  A 
        /   \
       B     C		先序序列:'A','B','D','E','C','F'
      / \   /   	中序序列:'D','B','E','A','F','C'
     D   E F		
//输出结果:
D
E
B
F
C
A

代码实现:


#include <iostream>
using namespace std;

typedef struct treenode{
    char data;
    struct treenode *lchild,*rchild;

}treenode, *tree;

int pos = 0;
tree build(char a[],char b[],int s,int e){
    if(s<=e){
        treenode *root = (treenode *)malloc(sizeof(treenode));
        root->data=a[pos];
        pos++;
        int i;
        for(i = s;i<=e;i++) if(b[i]==root->data) break;
        root->lchild = build(a,b,s,i-1);
        root->rchild = build(a,b,i+1,e);
        return root;
    }
    return NULL;
}

void outs(tree t){
    if(t){
        outs(t->lchild);
        outs(t->rchild);
        cout<<t->data<<endl;
    }
}
int main()
{
    char A[] = {'A','B','D','E','C','F'};
    char B[] = {'D','B','E','A','F','C'};
    tree root=build(A,B,0,5);
    cout<<"后序序列为:"<<endl;
    outs(root);
    return 0;
}


/*
          A 
        /   \
       B     C
      / \   /   
     D   E F
*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值