1. 程式人生 > >二叉排序樹遍歷

二叉排序樹遍歷

OJ傳送門

/*
 輸入一系列整數,建立二叉排序數,並進行前序,中序,後序遍歷
 */

#include <stdio.h>
#include <iostream>
using namespace std;
struct Node{
    Node *lchild;
    Node *rchild;
    int c;
}Tree[110];
int loc;

Node *creat(){
    Tree[loc].lchild=Tree[loc].rchild=NULL;
    return &Tree[loc++];
}

void postOrder(Node *T
){ if (T->lchild!=NULL) postOrder(T->lchild); if (T->rchild!=NULL) postOrder(T->rchild); printf("%-3d",T->c); } void inOrder(Node *T){ if (T->lchild!=NULL) postOrder(T->lchild); printf("%-3d",T->c); if (T->rchild!=NULL) inOrder(T
->rchild); } void preOrder(Node *T){ printf("%-3d",T->c); if (T->lchild!=NULL) postOrder(T->lchild); if (T->rchild!=NULL) preOrder(T->rchild); } Node *Insert(Node *T,int x){ if (T==NULL) { T=creat(); T->c=x; return T; } else
if(x<T->c) T->lchild=Insert(T->lchild, x); else if(x>T->c) T->rchild=Insert(T->rchild, x); return T; } int AVLTree(){ int n; Node *T = NULL; while (scanf("%d",&n)!=EOF) { for (int i=0; i<n; i++) { int x; cin>>x; T=Insert(T,x); } preOrder(T); putchar('\n'); inOrder(T); putchar('\n'); postOrder(T); putchar('\n'); } return 0; }