利用二叉树的两个遍历去写出二叉树(可算写完了)

#include<iostream>
#include<queue>
#include<malloc.h>
using namespace std;

typedef struct node {
    int data;
    struct node* left;
    struct node* right;
}Node;

typedef struct tree {
    Node* root;
}Tree;

int find(int arr[], int n)
{
    int i;
    for (i = 0; 1; i++)
    {
        if (arr[i] == n)
            return i;
    }
}

Node* creattree(int arr[], int brr[], int n)
{
    int i;
    if (n <= 0)
        return NULL;
    else
    {
        Node* ode = (Node*)malloc(sizeof(Node));
        ode->data = arr[n - 1];
        i = find(brr, arr[n - 1]);
        ode->left = creattree(arr, brr, i);
        ode->right = creattree(arr + i, brr + i + 1, n - i - 1);
        return ode;
    }

}

void mid(Node* n)
{
    if (n != NULL)
    {
        mid(n->left);
        printf("%d", n->data);
        mid(n->right);
    }
}

void ceng(Node* n)
{
    queue<Node*> p;
    p.push(n);
    int a[50],i = 0,k = 0;
    while (!p.empty())
    {
        Node* q = p.front();
        a[i++] = q->data;
        p.pop();
        if (q->left)
            p.push(q->left);
        if (q->right)
            p.push(q->right);
    }
    for (int j = 0; j < i; j++)
    {
        if (k == 0)
        {
            printf("%d", a[j]);
            k = 1;
        }
        else if (k)
            printf(" %d", a[j]);

    }
}

int main(void)
{
    int n, i, j;
    scanf("%d", &n);
    int one[n], two[n];
    for (i = 0; i < n; i++)
        scanf("%d", &one[i]);
    for (j = 0; j < n; j++)
        scanf("%d", &two[j]);
    Node* T;
    T = creattree(one, two, n);
    ceng(T);
    return 0;
}
 

 

posted @ 2020-12-15 20:13  loliconsk  阅读(54)  评论(0)    收藏  举报