二叉搜索树http://dsalgo.openjudge.cn/dsmoochw6/2/,答案正确,可惜运行时间超标
#include<stdio.h> #include<stdlib.h> #define QueueMaxSize 50 //定义队列数组长度 #define StackMaxSize 20 //定义栈数组长度 typedef int ElemType; struct BTreeNode { ElemType data; struct BTreeNode* left; struct BTreeNode* right; }; ElemType* Find(struct BTreeNode* BST, ElemType x) { if (BST == NULL) return NULL; else { if (x == BST->data) //若结点值等于x则返回结点值域的地址 return &(BST->data); else if (x < BST->data) return Find(BST->left, x); //向左子树继续查找并直接返回 else return Find(BST->right, x);//向右子树继续查找并直接返回 } } ElemType* Find1(struct BTreeNode* BST, ElemType x) { while (BST != NULL) { if (x == BST->data) //若结点值等于x则返回结点值域的地址 return &(BST->data); else if (x < BST->data) BST = BST->left; else BST = BST->right; } return NULL; } void Insert(struct BTreeNode** BST, ElemType x) { if (*BST == NULL) //在为空指针的位置链接新结点 { struct BTreeNode* p = malloc(sizeof(struct BTreeNode)); p->data = x; p->left = p->right = NULL; *BST = p; } else if (x < (*BST)->data) //向左子树中完成插入运算 Insert(&((*BST)->left), x); else Insert(&((*BST)->right), x); //向右子树中完成插入运算 } void Insert1(struct BTreeNode** BST, ElemType x) { struct BTreeNode* p; struct BTreeNode* t = *BST, *parent = NULL; while (t != NULL) //为插入新元素寻找插入位置 { parent = t; if (x < t->data) t = t->left; else t = t->right; }//循环之后parent存储的是待插入位置的双亲结点 p = malloc(sizeof(struct BTreeNode)); p->data = x; p->left = p->right = NULL; if (parent == NULL) //若树为空,作为根结点插入 *BST = p; else if (x < parent->data) //链接到左指针域 parent->left = p; else parent->right = p; //链接到右指针域 } void CreateBSTree(struct BTreeNode** BST, ElemType a[], int n) { int i; *BST = NULL; for (i = 0; i < n; i++) Insert1(BST, a[i]); } void Inorder_int(struct BTreeNode* BT)//中序遍历,元素类型为int { if (BT != NULL) { printf("%d ", BT->data); Inorder_int(BT->left); Inorder_int(BT->right); } } void ClearBTree(struct BTreeNode** BT)//清除二叉树,使之变为一棵空树 { if (*BT != NULL) { ClearBTree(&((*BT)->left));//删除左子树 ClearBTree(&((*BT)->right));//删除右子树 free(*BT); //释放根结点 *BT = NULL; //置根指针为空 } } int main()//其中用到二叉树操作的函数都基本没变,只是元素类型换为int { int c, ch; struct BTreeNode* bst = NULL; while(scanf("%d",&c)) { Insert(&bst, c); ch = getchar();//获取回车符 if (ch == 10) break;//判断是否换行 } Inorder_int(bst); printf(" "); //system("pause"); ClearBTree(&bst); return 0; }