1. 程式人生 > >二叉樹建立和遍歷

二叉樹建立和遍歷

mil inorder 推斷 microsoft con 是否 font pac node

二叉樹創建遍歷規則:

1.先序:根-左-右

2.中序:左-根-右

3.後序:左-右-根


二叉樹定義和輔助函數例如以下:

struct node {  
    int data;  
    struct node* left;  
    struct node* right;  
};  
  
void visit(int data)  
{  
    printf("%d ", data);  
}  

int indata()
{
    int data;
    scanf("%d",&data);
    return data;
}




先序創建二叉樹:

struct node* CreateBiTree()//先序建立一個二叉樹  
{   
    char x; //x為根節點  
    struct node* t;   
    x=indata();  
    if (x==' ') /* 推斷當前子樹是否創建完畢*/   
        return NULL;   
    else   
    {   
        t=(struct node*)malloc(sizeof(struct node));   
        t->data=x;   
        t->left=CreateBiTree();   
        t->right=CreateBiTree();   
    }   
    return t;  
}  
先序遍歷二叉樹:

void preOrder(struct node* root)  
{  
    if (root == NULL)  
        return;  
    visit(root->data);  
    preOrder(root->left);  
    preOrder(root->right);  
}  



中序創建二叉樹:

struct node* CreateBiTree()//先序建立一個二叉樹  
{   
    char x; //x為根節點  
    struct node* t;   
    x=indata();  
    if (x==' ') /* 推斷當前子樹是否創建完畢*/   
        return NULL;   
    else   
    {  
        t=(struct node*)malloc(sizeof(struct node)); 
        t->left=CreateBiTree();  
        t->data=x;     
        t->right=CreateBiTree();   
    }   
    return t;  
}  
中序遍歷二叉樹:

void inOrder(struct node* root)  
{  
    if (root == NULL)  
        return;  
    inOrder(root->left);  
    visit(root->data);  
    inOrder(root->right);  
}  




後序創建二叉樹

struct node* CreateBiTree()//先序建立一個二叉樹  
{   
    char x; //x為根節點  
    struct node* t;   
    x=indata();  
    if (x==' ') /* 推斷當前子樹是否創建完畢*/   
        return NULL;   
    else   
    {  
        t=(struct node*)malloc(sizeof(struct node)); 
        t->left=CreateBiTree();    
        t->right=CreateBiTree();   
    	t->data=x;   
    }   
    return t;  
}  
後序遍歷二叉樹

void inOrder(struct node* root)  
{  
    if (root == NULL)  
        return;  
    inOrder(root->left);   
    inOrder(root->right);  
    visit(root->data); 
}  



轉載請註明作者:小劉





二叉樹建立和遍歷