两棵二叉排序树合并为一颗 -- 07年 数据结构最后一道 [专硕]@NEU

来源:互联网 发布:用php做一个表格 编辑:程序博客网 时间:2024/06/06 17:57
#include <stdio.h>#include <stdlib.h>#include <string.h>const int N = 105;struct Node {int value;struct Node* lchild;struct Node* rchild;};typedef struct Node Node;Node* creat() {Node* root;int v;scanf("%d", &v);if(v == -1) return NULL;root = (Node*)malloc(sizeof(Node));root->value = v;root->lchild = creat();root->rchild = creat();return root;}int insert(Node* root, int key) {Node* p = NULL, *par = NULL;Node* pNew = (Node*)malloc(sizeof(Node));if(NULL == pNew) return -1;pNew->value = key;pNew->lchild = NULL;pNew->rchild = NULL;if(NULL == root) {root == pNew;return 0;}else {p = root;while(NULL != p) {/* key 不在二叉排序树中定死了已经! */par = p;p = (p->value < key) ? p->rchild : p->lchild;}}if(par->value < key) {par->rchild = pNew;}else {par->lchild = pNew;}return 0;}void inos(Node* root1, Node* root2) {Node* p = root2;if(NULL == p) return;if(p->lchild) inos(root1, p->lchild);insert(root1, p->value);if(p->rchild) inos(root1, p->rchild);}void inorder(Node* root) {Node* p = root;if(NULL == p) return;if(p->lchild) inorder(p->lchild);printf("%d ", p->value);if(p->rchild) inorder(p->rchild);}int main() {Node* root1, *root2;root1 = 0, root2 = 0;root1 = creat();root2 = creat();inos(root1, root2);inorder(root1);printf("\n");return 0;}// 12 8 4 -1 -1 10 -1 -1 16 13 -1 -1 18 -1 -1// 17 6 2 -1 -1 9 -1 -1 24 19 -1 -1 26 -1 -1