该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
#define INVALID 0xffffffff
typedef struct BinarySearchTreeNode
{
int key;
int data;
struct BinarySearchTreeNode *left;
struct BinarySearchTreeNode *right;
struct BinarySearchTreeNode *parent;
} BSTree;
BSTree *InsertNodeBSTree(BSTree **root,int key,int data)
{
if (*root==NULL)
{
BSTree *node;
node=(BSTree *)malloc(sizeof(BSTree));
node->key=key;
node->data=data;
node->left=NULL;
node->right=NULL;
*root=node;
return *root;
}
if (keykey)
return InsertNodeBSTree(&(*root)->left,key,data);
else
if (key>(*root)->key)
return InsertNodeBSTree(&(*root)->right,key,data);
else //如果相等,插入失败
return (BSTree *)INVALID;
}
这是我写的递归插入,问题在于node->parent怎么设置,因为递归到最后输入的结点是&(*root)->right(假如是右孩子),(*root)->right肯定是NULL,你没法从中获得*root的信息,所以设不了它为插入节点的父节点。除非你在前一层递归进行判断(比如if ((*root)->right==NULL) ......;什么的),但代码会显的很冗余,体现不出递归的优势,在网上看了很多代码都没有写parent的,有大佬有办法么?