二叉树的多种遍历方法

二叉树遍历学习

1.给出满二叉树的前序遍历建树。

 

#include <stdio.h>
#include <stdlib.h>
//前提是已知树是满的
char cache[101];

typedef struct Node
{
    char data;
    struct Node *lchild,*rchild;
};
struct Node *root;
int cnt;
struct Node *Build_tree()
{
    struct Node *root;
    if(cache[cnt++]=='#')
    {
        root=NULL;
    }
    else
    {
        root = (struct Node *) malloc(sizeof(struct Node));
        root -> data = cache[cnt-1];
        root -> lchild = Build_tree();
        root -> rchild = Build_tree();
    }
    return root;
}
void in_order(struct Node *root)
{
    if(root!=NULL)
    {
        in_order(root -> lchild);
        printf("%c ",root -> data);
        in_order(root -> rchild);
    }
}
void clean(struct Node *root)
{
    if(root!=NULL)
    {
        clean(root -> lchild);
        clean(root -> rchild);
        free(root);
    }
}

int main ()
{
    int i;
    while(scanf("%s",cache)!=EOF)
    {
        cnt=0;
        root=Build_tree();
        in_order(root);
        clean(root);
        printf("\n");
    }
    return 0;
}

2.已知先序和中序,求后序遍历(poj2255)。

 

 

#include <iostream>
#include <cstdio>
#include <string.h>
#include <string>
using namespace std;
const int maxn=10005;
char preo[maxn],ino[maxn];
typedef struct Node
{
    char data;
    Node *lson,*rson;
};
struct Node *root;
Node* _build (int n,char *preo,char *ino)
{
    if(n<=0) return NULL;
    Node *node =new Node;
    for(int i=0;i<n;i++)
    {
        if(preo[0]==ino[i])
        {
            node -> data = ino[i];
            node -> lson = _build (i,preo+1,ino);
            node -> rson = _build (n-i-1,preo+i+1,ino+i+1);
            break;
        }
    }
    return node;
}
void print(struct Node *node)
{
    if(node)
    {
        print(node->lson);
        print(node->rson);
        if(node==root)
        {
            printf("%c\n",node->data);
        }
        else
        {
            printf("%c",node -> data);
        }
    }
}
int main ()
{
    while(scanf("%s %s",preo,ino)!=EOF)
    {
        int len=strlen(ino);
        root=_build(len,preo,ino);
        print(root);
    }
    return 0;
}
 

3.已知后序和中序,求先序。

 

 

Node* build (int n, int* ino, int* post)
{
    Node* node = new Node;
    int i = n - 1;
    if (n <= 0)
        return NULL;
    while (ino[i] != post[n - 1])
        i--;
    node -> val = ino[i];
    node -> left = build(i, ino, post);
    node -> right = build(n - i - 1, ino + i + 1, post + i);
    return node;
}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值