若原树为空,生成并返回一个结点的二叉搜索树
若不为空,X与树的根结点的键值相比较
若X大,则向右子树插入
若X小,则向左子树插入
//定义二叉树
typedef struct TreeNode *BinTree;
typedef BinTree Position;
typedef int ElementType;
struct TreeNode
{
ElementType data;
BinTree left;
BinTree right;
};
BinTree Insert(ElementType x,BinTree bst)
{
if(!bst) //如果为空,生成并返回只有一个结点的二叉树
{
bst=(BinTree)malloc(sizeof(TreeNode));
bst->data=x;
bst->left=bst->right=NULL;
}
else
{
if(x<bst->data)
bst->left=Insert(x,bst->left);
else if(x>bst->data)
bst->right=Insert(x,bst->right);
//x已经存在,什么都不做
}
return bst;
}