二叉树的具体存储方式以及遍历顺序
首先我们得会自己创建一个二叉树,其实原理和链表差不多,一个数据域,和俩个指针域分别指向他的左孩子和右孩子。
具体代码如下 :
//二叉链表的结点结构定义
typedef int TElemType;
typedef struct BiTNode {
TElemType data;
struct BiTNode* lchild, * rchild;
}BiTNode,*BiTree;
//创建新结点
BiTree CreateNode(TElemType data) {
BiTree newNode = (BiTree)malloc(sizeof(BiTNode));
newNode->data = data;
newNode->lchild = NULL;
newNode->rchild = NULL;
return newNode;
}
然后就是遍历顺序
有递归版本,也就是前中后序遍历顺序
前序是:中左右
后序是:左右中
中序是:左中右
具体可以验证并检验的代码如下、
#include<stdio.h>
#include<stdlib.h>
//前序
void preOrder(BiTree root, int* ret, int* returnSize) {
if (root == NULL) {
return;
}
ret[(*returnSize)++] = root->data;
preOrder(root->lchild, ret, returnSize);
preOrder(root->rchild, ret, returnSize);
}
int* preorderTraversal(BiTree root, int* returnSize) {
int* ret = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
preOrder(root, ret, returnSize);
return ret;
}
//中序
void inOrder(BiTree node, int* ret, int* returnSize) {
if (node==NULL)
return;
inOrder(node->lchild, ret, returnSize);
ret[(*returnSize)++] = node->data;
inOrder(node->rchild, ret, returnSize);
}
int* inorderTraversal(BiTree root, int* returnSize) {
int* ret = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
inOrder(root, ret, returnSize);
return ret;
}
//后序
void postOrder(BiTree node, int* ret, int* returnSize) {
if (!node) {
return;
}
postOrder(node->lchild, ret, returnSize);
postOrder(node->rchild, ret, returnSize);
ret[(*returnSize)++] = node->data;
}
int* postorderTraversal(BiTree* root, int* returnSize) {
int* ret = (int*)malloc(sizeof(int) * 100);
*returnSize = 0;
postOrder(root, ret, returnSize);
return ret;
}
void Test1(BiTree root) {
//初始化
int len = 0;
//int* ret = preorderTraversal(root, &len);
int* ret = inorderTraversal(root, &len);
//int* ret = postorderTraversal(root, &len);
//打印遍历结果
for (int i = 0; i < len; i++)
printf("%d ", ret[i]);
printf("\n");
free(ret);
return;
}
int main() {
//创建二叉树
BiTree root = CreateNode(1);
root->lchild= CreateNode(2);
root->rchild = CreateNode(3);
root->lchild->lchild = CreateNode(4);
root->lchild->rchild = CreateNode(5);
Test1(root);
return 0;
}