数据结构实验——二叉树实验

xiaoxiao2021-02-27  288

实验要求

实验源代码

#include <stdio.h> #include <malloc.h> typedef struct TREE{ int data; struct TREE *left; struct TREE *right; }Tree,*linkTree; linkTree creatTree(int data); // 中序遍历 void inorderTree(linkTree tree); // 先序遍历 void preorderTree(linkTree tree); // 后序遍历 void postorderTree(linkTree tree); int main(){ linkTree head = creatTree(1); head->left = creatTree(2); head->right = creatTree(3); head->right->left = creatTree(4); head->right->left->left = creatTree(6); head->right->right = creatTree(5); preorderTree(head); printf("\n"); postorderTree(head); printf("\n"); inorderTree(head); printf("\n"); return 0; } linkTree creatTree(int data){ linkTree tree = (linkTree)malloc(sizeof(Tree)); tree->data = data; tree->left = NULL; tree->right = NULL; return tree; } /* 三种遍历说到底就是改变printf的相对位置 */ // 1 2 3 4 6 5 void preorderTree(linkTree tree){ if(tree != NULL){ printf("%d\t",tree->data); preorderTree(tree->left); preorderTree(tree->right); } } // 2 6 4 5 3 1 void postorderTree(linkTree tree){ if(tree != NULL){ postorderTree(tree->left); postorderTree(tree->right); printf("%d\t",tree->data); } } // 2 1 6 4 3 5 void inorderTree(linkTree tree){ if(tree != NULL){ inorderTree(tree->left); printf("%d\t",tree->data); inorderTree(tree->right); } }

实验结果显示

转载请注明原文地址: https://www.6miu.com/read-4211.html

最新回复(0)