手搓模拟实现一个二叉树,其数据为:1 2 3 4 5 6

前序遍历为:1 2 3 NULL NULL NULL 4 5 NULL NULL 6 NULL NULL
中序遍历为:NULL 3 NULL 2 NULL 1 NULL 5 NULL 4 NULL 6 NULL
后序遍历为:NULL NULL 3 NULL 2 NULL NULL 5 NULL NULL 6 4 1
前序遍历逻辑图

中序遍历逻辑图

后序遍历逻辑图

代码如下:
typedef int BTDataType;
typedef struct BinaryTreeNode
{
BTDataType data;//数据
struct BinaryTreeNode* left;//左子树
struct BinaryTreeNode* right;//右子树
}BTNode;
BTNode* BuyNode(BTDataType x)//创建节点
{
BTNode* tmp = (BTNode*)malloc(sizeof(BTNode));//申请空间
if (tmp==NULL)
{
perror("malloc");
return;
}
tmp->data = x;
tmp->left = tmp->right = NULL;//将左右字数置空
return tmp;//返回申请空间地址
}
BTNode* CreatTree()//模拟创建一个数
{
BTNode* node1 = BuyNode(1);
BTNode* node2 = BuyNode(2);
BTNode* node3 = BuyNode(3);
BTNode* node4 = BuyNode(4);
BTNode* node5 = BuyNode(5);
BTNode* node6 = BuyNode(6);
node1->left = node2;
node1->right = node4;
node2->left = node3;
node4->left = node5;
node4->right = node6;
return node1;
}
void PreOrder(BTNode* root)//前序遍历
{
if (root==NULL)
{
printf("NULL ");
return;
}
printf("%d ", root->data);
PreOrder(root->left);
PreOrder(root->right);
}
void InOrder(BTNode* root)//中序遍历
{
if (root == NULL)
{
printf("NULL ");
return;
}
InOrder(root->left);
printf("%d ", root->data);
InOrder(root->right);
}
void PostOrder(BTNode* root)//后序遍历
{
if (root == NULL)
{
printf("NULL ");
return;
}
PostOrder(root->left);
PostOrder(root->right);
printf("%d ", root->data);
}
int main()
{
BTNode* root = CreatTree();
PreOrder(root);
printf("\\n");
InOrder(root);
printf("\\n");
PostOrder(root);
printf("\\n");
return 0;
}

