1. 程式人生 > >二叉樹的多種遍歷方法

二叉樹的多種遍歷方法

二叉樹遍歷學習

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;
}