根据二叉树中序遍历的非递归算法,在二叉树t查找值为x的元素,若找到且其左子树为空,则将值为y的元素插入成为其左孩子,否则若其右孩子为空,则将y插入成为其右孩子。插入失败,返回值为0,否则返回值为1。
int inserttree(BiTree &T, TElemType x, TElemType y)
{ }
在主函数中分别调用上述函数,测试数据采用下列两颗二叉树:
分别对上述两颗二叉树的数据进行测试,并给出运行结果。
相关类型的申明:
typedef int TElemType;
typedef struct BiTNode
{
TElemType data;
struct BiTNode *lchild, *rchild;
} BiTNode, *BiTree;
typedef BiTree SElemType;//栈元素类型
typedef struct
{
SElemType *base;
SElemType *top;
int stacksize;
} SqStack;
主函数的主要形式:
int main()
{
BiTree t;
TElemType x,y;
printf("输入树的相关数据,以-1结束.\n");
createtree(t);
//分别调用三种遍历算法,以输出三种遍历序列
inorder(t);
printf("\n");
preorder(t);
printf("\n");
postorder(t);
printf("\n");
printf("输入要查找的元素x和要插入的元素y.\n");
scanf("%d%d",&x,&y);
if(inserttree(t,x,y)){
printf("插入元素%d后的树的三种遍历序列为:\n",y);
inorder(t);
printf("\n");
preorder(t);
printf("\n");
postorder(t);
printf("\n");
}
else printf("插入不成功!\n");
return 1;
}