本文主要是介绍非线性结构之二叉树,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
二叉树的建立和遍历
#include<stdio.h>
#include<malloc.h>
#include<string.h>
typedef struct tree{
int data;
struct tree *leftNode;
struct tree *rightNode;
}tree;
tree * createTree();
void proTraversal(tree *root);
void InoTraversal(tree *root);
void posTraversal(tree *root);
int main()
{
tree *root;
root = createTree();
printf("先序遍历:\n");
proTraversal(root);
printf("中序遍历:\n");
InoTraversal(root);
printf("后序遍历:\n");
posTraversal(root);
return 0;
}
tree * createTree()
{
tree *root,*pn1,*pn2,*pn3,*pn4,*pn5,*pn6 = NULL;
//存储节点
root=(tree *)malloc(sizeof(tree));
root->data = 0;
pn1=(tree *)malloc(sizeof(tree));
pn1->data = 1;
pn2=(tree *)malloc(sizeof(tree));
pn2->data = 2;
pn3=(tree *)malloc(sizeof(tree));
pn3->data = 3;
pn4=(tree *)malloc(sizeof(tree));
pn4->data = 4;
pn5=(tree *)malloc(sizeof(tree));
pn5->data = 5;
pn6=(tree *)malloc(sizeof(tree));
pn6->data = 6;
//存储关系
root->leftNode = pn1;
root->rightNode = pn2;
pn1->leftNode = pn3;
pn1->rightNode = pn4;
pn2->leftNode = pn5;
pn2->rightNode = pn6;
pn3->leftNode = NULL;
pn3->rightNode = NULL;
pn4->leftNode = NULL;
pn4->rightNode = NULL;
pn5->leftNode = NULL;
pn5->rightNode = NULL;
pn6->leftNode = NULL;
pn6->rightNode = NULL;
//返回头节点
return root;
}
void proTraversal(tree *root)
{
if(root!=NULL)
{
printf("%d\n",root->data);
proTraversal(root->leftNode);
proTraversal(root->rightNode);
}
}
void InoTraversal(tree *root)
{
if(root!=NULL)
{
InoTraversal(root->leftNode);
printf("%d\n",root->data);
InoTraversal(root->rightNode);
}
}
void posTraversal(tree *root)
{
if(root!=NULL)
{
posTraversal(root->leftNode);
posTraversal(root->rightNode);
printf("%d\n",root->data);
}
}
这篇关于非线性结构之二叉树的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!