完全二叉樹的遍歷

Stephen_X_x發表於2019-05-22
#include<cstdio>
#include<cstdlib>
#include<iostream>
#include<queue>
#include<algorithm>
using namespace std;

int data[100];
int xx=0,n;
typedef struct TreeNode {
    int data;
    struct TreeNode *left;
    struct TreeNode *right;
    struct TreeNode *parent;
} TreeNode;

queue<TreeNode* > q;

void pre_order(TreeNode * Node)
{
    if(Node != NULL)
    {
        printf("%d ", Node->data);
        pre_order(Node->left);
        pre_order(Node->right);
    }
}
void post_order(TreeNode * Node)
{
    if(Node != NULL)
    {
        post_order(Node->left);
        post_order(Node->right);
        printf("%d ", Node->data);
    }
}
void middle_order(TreeNode *Node) {
    if(Node != NULL) {
        middle_order(Node->left);
        printf("%d ", Node->data);
        middle_order(Node->right);
    }
}
void build()
{
    TreeNode *Node=q.front();
    q.pop();
    xx++;
    if(xx<=n)
    {
        Node->data=data[xx-1];
        TreeNode *s1=new TreeNode;
        TreeNode *s2=new TreeNode;
        s1->parent=Node;
        s2->parent=Node;
        Node->left=s1;
        Node->right=s2;
        q.push(Node->left);
        q.push(Node->right);
    }
    else
    {
        if((Node->parent)->left==Node)
            (Node->parent)->left=NULL;

        if((Node->parent)->right==Node)
            (Node->parent)->right=NULL;
            //very important
        Node=NULL;
//      Node->left=NULL;
//      Node->right=NULL;
    }
}

int main()
{
    freopen("in.txt","r",stdin);

    int temp;
    n=0;
    while (scanf("%d",&temp)!=EOF)
    {
        n++;
        data[n-1]=temp;
    } 
//    Init(data,&T,n);
    TreeNode *T;
    T->left=NULL;
    T->right=NULL;
    q.push(T);
    while(!q.empty())
        build();
    cout<<"Tree size is: "<<n<<endl;
    int Dep=1;
    temp=n;
    while(temp/2!=0)
    {
        temp/=2;
        Dep++;
    }
    cout<<"Tree height is: "<<Dep<<endl;
    cout<<"Preorder:"<<endl;
    pre_order(T);
    cout<<endl;
    cout<<"Inorder:"<<endl;
    middle_order(T);
    cout<<endl;
    cout<<"Postorder:"<<endl;
    post_order(T);
    return 0;
}
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章