兩棵二叉排序樹合併為一顆 -- 07年 資料結構最後一道 [專碩]@NEU
阿新 • • 發佈:2019-01-01
#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