二叉排序樹的合併(嚴9.38)
阿新 • • 發佈:2019-01-02
Description
試編寫程式,將兩棵二叉排序樹合併為一棵二叉排序樹。
Input
按照先序序列,分兩行輸入兩棵二叉排序樹各結點(結點值大於0),其中-1表示取消建立子樹結點。
Output
按照中序序列輸出合併後的二叉排序樹。
- Sample Input
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
- Sample Output
2 4 6 8 9 10 12 13 16 17 18 19 24 26
#include<stdio.h> #include<stdlib.h> typedef struct BinNode{ int data; struct BinNode *lchild; struct BinNode *rchild; }BinNode,*BinTree; void CreateBinTree(BinTree *tree) { int ch; scanf("%d",&ch); if(ch == -1) { (*tree) = NULL; } else { *tree = (BinTree)malloc(sizeof(BinNode)); (*tree)->data = ch; CreateBinTree(&((*tree)->lchild)); CreateBinTree(&((*tree)->rchild)); } } void Inorder(BinTree T) { if(T) { Inorder(T->lchild); printf("%d ",T->data); Inorder(T->rchild); } } void Insert(BinTree *T,int key) { if(!(*T)) { (*T) = (BinTree)malloc(sizeof(BinNode)); (*T)->data = key; (*T)->lchild = (*T)->rchild = NULL; return; } if(key == (*T)->data ) return; if(key > (*T)->data ) Insert( &((*T)->rchild), key ); else Insert( &((*T)->lchild), key ); } void InsertBST(BinTree T1,BinTree T2) { if(T2) { InsertBST(T1,T2->lchild); Insert(&T1,T2->data); InsertBST(T1,T2->rchild); } } int main(){ BinTree T1 = NULL; BinTree T2 = NULL; CreateBinTree(&T1); CreateBinTree(&T2); InsertBST(T1,T2); Inorder(T1); printf("\n"); return 0; }
把上一題的程式碼改改就能過,主要想法就是把一棵樹插入到另一棵樹裡