gpt-3.5-turbo-0301· OpenAI WildChat-4.8M (AI2)
用c语言代码实现如下操作:1)二叉树结点类型定义为: typedef struct bnode { int data; struct bnode lc, rc; }BNode;…
- User
用c语言代码实现如下操作:1)二叉树结点类型定义为: typedef struct bnode { int data; struct bnode *lc, *rc; }BNode; 2)编写中序遍历函数; 3)编写后序遍历函数; 4)编写先序遍历函数; 5)编写create函数,按照先序遍历方法根据输入的字母序列建立二叉树; 6)编写二叉排序树的创建函数(可用递归方法); 7)编写main( )函数,分别创建5)6)两种二叉树;然后分别调用中序、后序、先序遍历函数进行遍历。
- Assistant
1)二叉树结点类型定义为:
typedef struct bnode { int data; struct bnode *lc, *rc; }BNode;2)中序遍历函数:
void inOrder(BNode *root) { if(root != NULL) { inOrder(root->lc); printf("%d ", root->data); inOrder(root->rc); } }3)后序遍历函数:
void postOrder(BNode *root) { if(root != NULL) { postOrder(root->lc); postOrder(root->rc); printf("%d ", root->data); } }4)先序遍历函数:
void preOrder(BNode *root) { if(root != NULL) { printf("%d ", root->data); preOrder(root->lc); preOrder(root->rc); } }5)create函数:
BNode *create() { char c; scanf("%c", &c); if(c == ' ') return NULL; else { BNode *node = (BNode*)malloc(sizeof(BNode)); node->data = c; node->lc = create(); node->rc = create(); return node; } }6)二叉排序树的创建函数:
BNode *insert(BNode *root, int data) { if(root == NULL) { BNode *node = (BNode*)malloc(sizeof(BNode)); node->data = data; node->lc = NULL; node->rc = NULL; return node; } else if(data < root->data) root->lc = insert(root->lc, data); else if(data > root->data) root->rc = insert(root->rc, data); return root; }7)main函数:
int main() { BNode *tree1 = create(); printf("In-order Traversal of tree1: "); inOrder(tree1); printf("\nPost-order Traversal of tree1: "); postOrder(tree1); printf("\nPre-order Traversal of tree1: "); preOrder(tree1); BNode *tree2 = NULL; int arr[5] = {5, 3, 1, 4, 7}; for(int i = 0; i < 5; i++) tree2 = insert(tree2, arr[i]); printf("\nIn-order Traversal of tree2: "); inOrder(tree2); printf("\nPost-order Traversal of tree2: "); postOrder(tree2); printf("\nPre-order Traversal of tree2: "); preOrder(tree2); return 0; }