上篇介紹了二叉樹的理論部分矫户,這篇貼出二叉樹完整的C語言代碼實現(xiàn)。
BinaryTree.c
#include <stdio.h>
#include <stdlib.h>
typedef int TElemTpye;
typedef struct BinaryTreeNode{
TElemTpye data;
struct BinaryTreeNode *left,*right;
}BinaryTreeNode,*BinaryTree;
/**
* 初始化樹残邀,創(chuàng)建根節(jié)點
* @return
*/
BinaryTree InitBinaryTree(){
BinaryTree root; //根節(jié)點
TElemTpye rootVal;
root = (BinaryTree)malloc(sizeof(BinaryTreeNode));
printf("請輸入根節(jié)點:\n");
scanf("%d",&rootVal);
if(rootVal <= 0){
printf("請輸入大于0的數(shù)皆辽,否則為空樹");
exit(0);
}
root->data = rootVal;
root->left = NULL;
root->right = NULL;
return root;
}
/**
* 創(chuàng)建二叉樹
* @param T
*/
void CreateBinaryTree(BinaryTree *T){
TElemTpye val;
BinaryTree node;
printf("請輸入%d的左子節(jié)點\n",(*T)->data);
scanf("%d",&val);
if(val <= 0){ //val小于等于0都表示空樹,這里是為了方便才這么寫芥挣,其實0和負(fù)數(shù)是可以作為二叉樹的節(jié)點的
node = NULL;
return;
}
if(val >0){
node =(BinaryTree) malloc(sizeof(BinaryTreeNode));
if(!node)
exit(-1);
(node)->data = val;
node->left = NULL;
node->right = NULL;
(*T)->left = node;
CreateBinaryTree(&(*T)->left);
}
printf("請輸入%d的右子節(jié)點\n",(*T)->data);
scanf("%d",&val);
if(val > 0){
node =(BinaryTree) malloc(sizeof(BinaryTreeNode));
if(!node)
exit(-1);
node->data = val;
node->left = NULL;
node->right = NULL;
(*T)->right = node;
CreateBinaryTree(&(*T)->right);
}
}
/**
* 二叉樹的前序遍歷
* @param binaryTree
*/
void PreOrder(BinaryTree node){
if(node == NULL)
return;
printf("%d",node->data);
PreOrder(node->left);
PreOrder(node->right);
}
/**
* 二叉樹的中序遍歷
* @param binaryTree
*/
void InOrder(BinaryTree node){
if(node == NULL)
return;
InOrder(node->left);
printf("%d",node->data);
InOrder(node->right);
}
/**
* 二叉樹的后序遍歷
* @param binaryTree
*/
void PostOrder(BinaryTree node){
if(node == NULL)
return;
PostOrder(node->left);
PostOrder(node->right);
printf("%d",node->data);
}
BinaryTree.h
#ifndef TEST_BINARYTREE_H
#define TEST_BINARYTREE_H
typedef int TElemTpye;
typedef struct BinaryTreeNode{
TElemTpye data;
struct BinaryTreeNode *left,*right;
}BinaryTreeNode,*BinaryTree;
//初始化樹膳汪,創(chuàng)建根節(jié)點
BinaryTree InitBinaryTree();
//創(chuàng)建一棵二叉樹
void CreateBinaryTree(BinaryTree *T);
//二叉樹的前序遍歷
void PreOrder(BinaryTree binaryTree);
//二叉樹的中序遍歷
void InOrder(BinaryTree binaryTree);
//二叉樹的后序遍歷
void PostOrder(BinaryTree binaryTree);
main.c
BinaryTree root;
root = InitBinaryTree();
CreateBinaryTree(&root);
//前序遍歷
PreOrder(root);
printf("\n");
//中序遍歷
InOrder(root);
printf("\n");
//后序遍歷
PostOrder(root);
printf("\n");
運行結(jié)果
請輸入根節(jié)點:
1
請輸入1的左子節(jié)點
2
請輸入2的左子節(jié)點
4
請輸入4的左子節(jié)點
8
請輸入8的左子節(jié)點
0
請輸入4的右子節(jié)點
9
請輸入9的左子節(jié)點
0
請輸入2的右子節(jié)點
5
請輸入5的左子節(jié)點
0
請輸入1的右子節(jié)點
3
請輸入3的左子節(jié)點
6
請輸入6的左子節(jié)點
0
請輸入3的右子節(jié)點
7
請輸入7的左子節(jié)點
0
124895367
849251637
894526731