实现二叉树并对其进行遍历操作
二叉树概念不做解释了,使用二级指针进行操作,比较方便。
使用时节点值须大于0,否则该节点置为NULL。
环境:Ubuntu18.04 GCC编译通过并使用
Code:
#include <stdio.h>
#include <stdlib.h>
//节点
struct BinTreeNode
{
int value;
struct BinTreeNode *left;
struct BinTreeNode *right;
};
//创建树
int CreatBinTree(struct BinTreeNode **root)
{
int val;
scanf("%d", &val);
if (val <= 0)
{
*root = NULL;
return 0;
}
*root = (struct BinTreeNode*)malloc(sizeof(struct BinTreeNode));
if (!(*root))
{
perror("Failed to creat:");
return -1;
}
else
{
(*root)->value = val;
printf("%d Left sibling:", val);
CreatBinTree(&((*root)->left));
printf("%d Right sibling:", val);
CreatBinTree(&((*root)->right));
}
return 0;
}
//前序遍历
int PreorderTraversal(struct BinTreeNode *root)
{
if (!root)
return -1;
printf("%d,", root->value);
PreorderTraversal(root->left);
PreorderTraversal(root->right);
return 0;
}
//后序遍历
int PostorderTraversal(struct BinTreeNode *root)
{
if (!root)
return -1;
PostorderTraversal(root->left);
PostorderTraversal(root->right);
printf("%d,", root->value);
return 0;
}
//中序遍历
int InorderTraversal(struct BinTreeNode *root)
{
if (!root)
return -1;
InorderTraversal(root->left);
printf("%d,", root->value);
InorderTraversal(root->right);
return 0;
}
int main(int argc, char const *argv[])
{
struct BinTreeNode *root = (struct BinTreeNode*)malloc(sizeof(struct BinTreeNode*));
CreatBinTree(&root);
printf("Preorder Traversal:\n");
PreorderTraversal(root);
printf("\n");
printf("Inorder Traversal:\n");
InorderTraversal(root);
printf("\n");
printf("Postorder Traversal:\n");
PostorderTraversal(root);
printf("\n");
return 0;
}
Picture: