1. 程式人生 > >c語言使用指標實現二叉樹遍歷

c語言使用指標實現二叉樹遍歷

使用指標實現二叉樹的定義,建立,以及前序遍歷,中序遍歷,後續遍歷。

/*
該程式實現了二叉樹的建立,以及樹的遍歷,前序遍歷,中序遍歷,後序遍歷。

*/
#include <stdio.h>
#include<stdlib.h>
#include <sys/malloc.h>

typedef struct tree_node
{
    char data;
    struct tree_node *lchild,*rchild;
}BT_Node;//宣告一個結構體,包含根節點,左右子樹
#define Tree_NodeLen sizeof(BT_Node)
BT_Node *tree;//定義結構體指標,指向新建立的二叉樹
//函式宣告
BT_Node *Creat_BTree(BT_Node *tree);

void Visit_Node(BT_Node *tree);
void Pre_Order(BT_Node *tree);
void Mid_Order(BT_Node *tree);
void After_Order(BT_Node *tree);

int main(void)
{
    printf("\n 請輸入樹結點 :\n ");
    tree = Creat_BTree(tree);
    if(tree)
    {
        printf("\n 前序遍歷:\n ");
        Pre_Order(tree);
        printf("\n");


        printf("\n 前序遍歷:\n ");
        Mid_Order(tree);
        printf("\n");

        printf("\n 前序遍歷:\n ");
        After_Order(tree);
        printf("\n");
    }
    printf("\n");
    return 0;
}
BT_Node *Creat_BTree(BT_Node *tree)
{
    char ch ;
    ch = getchar();

    if(ch == '*')
    {
        tree = NULL;
    }
    else
    {
        tree = (BT_Node *)malloc(Tree_NodeLen);
        tree->data = ch;
        tree->lchild = Creat_BTree(tree->lchild);
        tree->rchild = Creat_BTree(tree->rchild);
    }
    return(tree);
}
//該函式實現將字母顯示到終端
void Visit_Node(BT_Node *tree)
{
    printf(" ");
    putchar(tree->data);
    printf("\t");
}
//實現前序遍歷··
void Pre_Order(BT_Node *tree)
{
    if(!tree)
    {
        return;
    }
    else
    {
        Visit_Node(tree);
        Pre_Order(tree->lchild);
        Pre_Order(tree->rchild);
    }
}
//實現中序遍歷
void Mid_Order(BT_Node *tree)
{
    if(!tree)
    {
        return;
    }
    else
    {
        Mid_Order(tree->lchild);
        Visit_Node(tree);
        Mid_Order(tree->rchild);
    }

}

//實現後序遍歷

void After_Order(BT_Node *tree)
{
    if(!tree)
    {
        return;
    }
    else
    {
        After_Order(tree->lchild);
        After_Order(tree->rchild);
        Visit_Node(tree);
    }
}
實現的結果:
請輸入樹結點 :
 abd**e*hj***cf**g**

 前序遍歷:
  a	 b	 d	 e	 h	 j	 c	 f	 g	

 前序遍歷:
  d	 b	 e	 j	 h	 a	 f	 c	 g	

 前序遍歷:
  d	 j	 h	 e	 b	 f	 g	 c	 a