感谢参考
名字:
二叉排序树又称为二叉搜索树和二叉查找树
概念:
以下情况可以定义一棵二叉排序树
a)空树
b)左子节点不为空,则左子树节点值都小于根节点
+右子节点不为空,则右子树节点值都大于根节点
+左右子树都是二叉排序树
特性:
a)二叉排序树中没有value相同的节点
b)二叉排序树中序遍历可得出一个升序序列
c)二叉排序树的搜索、插入、删除复杂度都是o(n)
最大节点:
思路:
一路向右
代码:
/*
最大节点在右子树
*/
BitTree* max(BitTree *root)
{
if(!root) return;
while(root->right)
{
root = root->right;
}
return root;
}
最小节点:
思路:
一路向左
代码:
/*
最小节点在左子树
*/
BitTree* min(BitTree *root)
{
if(!root) return;
while(root->left)
{
root = root->left;
}
return root;
}
在子树中获取直接后继:
思路:
跟最小节点相似。直接后继是右子树中的最小节点
代码:
/*
在root的子树中获取root的直接后继(即比root大,但差值最小的)
*/
BitTree* psotNearest(BitTree *root)
{
if(!root) return;
else if(!root->right) return root;
else
{
/*
可以这个来代替
root = min(root->right);
*/
root = root->right;
while(root->left) root = root->left;
return root;
}
}
/*
当然我们也应该了解在整棵树中寻找直接后继;当然前提是有回溯指针parent
*/
BitTree* preNearest(BitTree *root)
{
if(!root) return;
//没有右子树,则直接后继在上层
else if(!root->right)
{
while(root->parent && root->parent->right == root) root = root->parent;
return root->parent;
}
else
{
/*
可以这个来代替
root = min(root->right);
*/
root = root->right;
while(root->left) root = root->left;
return root;
}
}
在子树中获取直接前驱:
思路:
跟最小节点相似。直接前驱是左子树中的最大节点
代码:
/*
在root的子树中获取root的直接前驱(即比root小,但差值最小的)
*/
BitTree* preNearest(BitTree *root)
{
if(!root) return;
else if(!root->left) return root;
else
{
/*
可以这个来代替
root = min(root->left);
*/
root = root->left;
while(root->right) root = root->right;
return root;
}
}
*/
BitTree* preNearest(BitTree *root)
{
if(!root) return;
//没有左子树,则直接前驱在上层
else if(!root->left)
{
while(root->parent && root->parent->left == root) root = root->parent;
return root->parent;
}
else
{
/*
可以这个来代替
root = min(root->left);
*/
root = root->left;
while(root->right) root = root->right;
return root;
}
}
搜索:
思路:
将查找节点与当前节点作比较
a)相等,则查找成功
b)find>root,则search(root->right)
c)find<root,则search(root->left)
代码:
/*
search in bst(bit sorted tree)
*/
bool search(BitTree *root, BitTree *find)
{
if(!root) return false;
else if(root == find) return ture;
else if(root > find) return search(root->left, find);
else return search(root->right, find);
}
插入:
思路:
递归寻找合适的位置,直至找到叶子节点,然后将叶子节点的左孩子或者右孩子变为node
代码:
/*
insert in bst(bit sorted tree)
*/
void insert(BitTree *root, BitTree *node)
{
if(!root) return;
else if(root == node) return;
else
{
bool isLeaf = (!root->left && !root->right);
if(root > node)
{
isLeaf? root->left = node:insert(root->left, node);
}
else
{
isLeaf? root->right = node:insert(root->left, node);
}
}
}
/*
insert in bst(bit sorted tree), without recurse
*/
void insertNoRec(BitTree *root, BitTree *node)
{
if(!root) return ;
BitTree *parent;
while(root)
{
parent = root;
if(node == root) return;
root = (root > node? root->left:root->right);
}
node = (node > parent? parent->right : parent->left);
}