二叉查找树(BST)AS3版

本文详细介绍了二叉查找树(BST)的概念与实现原理,包括其定义、关键属性及核心操作如插入、删除等,并提供了具体的代码实现示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

也称为二叉搜索树或者二叉排序树(Binary Search Tree)二叉查找树或者是一棵空树,或者是具有下列性质的二叉树:
1、每个结点都有一个作为查找依据的关键码(key),所有结点的关键码互不相同。
2、左子树(如果存在)上所有结点的关键码都小于根结点的关键码。
3、右子树(如果存在)上所有结点的关键码都大于根结点的关键码。
4、左子树和右子树也是二叉查找树。

定义一个BST:


package kono.utils.collections
{
import kono.utils.BTnode;

//二叉查找树(BST), binary search tree (BST)
public class BStree implements Icollection
{
//二叉查找树根结点, the root node of the binary search tree
private var tree:BTnode;

//查找判断的依据函数,
//the compare function will use to confirm that the left child????s data is less than the current data,
//while the right child????s data is greater than the current data
private var compare:Function;

//默认的判断函数判读的依据是BST存储了整数, default function used for the integer comparing
public function BStree(compareTo:Function = null)
{
tree = null;
if(compareTo == null)
{
compare = function(a:Number, b:Number):int
{
return int(a - b);
}
}
else
{
compare = compareTo;
}
}

//增加一个数据到BST, add a new data to BST
public function add(data:*):void
{
var cursor:BTnode = tree;
var done:Boolean = true;
if(!tree)
{
tree = new BTnode(data);
}
else
{
while(done)
{
if(compare(data, cursor.nodeData) <= 0)
{
if(cursor.leftChild)
{
cursor = cursor.leftChild;
}
else
{
cursor.leftChild = new BTnode(data);
done = false;
}
}
else
{
if(cursor.rightChild)
{
cursor = cursor.rightChild;
}
else
{
cursor.rightChild = new BTnode(data);
done = false;
}
}
}
}
}

//从BST中删除一个指定数据, remove a given data from the BST;
//@ target: 要删除的数据,如果删除成功返回true,失败或未找到返回false,
//@ target: to remove from the BST, return true if success, and return false if failed or can not find it in the BST
public function remove(target:*):Boolean
{
var cursor:BTnode = tree;
var parentCursor:BTnode = null;
var t:int;
while(cursor)
{
t = compare(target, cursor.nodeData)
if(t == 0)
{
if(cursor == tree && cursor.leftChild == null)
{
tree = tree.rightChild;
return true;
}
if(cursor.leftChild == null)
{
if(cursor == parentCursor.leftChild)
{
parentCursor.leftChild = cursor.rightChild;
return true;
}
else
{
parentCursor.rightChild = cursor.leftChild;
return true;
}
}
else
{
cursor.nodeData = cursor.leftChild.rightMostData;
cursor.leftChild.removeRightMost();
return true;
}
}
else
{
parentCursor = cursor;
cursor = t < 0 ? cursor.leftChild : cursor.rightChild;
}
}
return false;
}

//清空BST, clear all the items in the BST
public function clear():void
{
tree = new BTnode(null);
tree = null;
}

//返回BST中包含的结点, get the total number in the BST
public function get size():uint
{
return BTnode.getSize(tree);
}

//中序转换结点数据到array中, write all of the data in the BST into a Array
public function toArray():Array
{
var a:Array = new Array();
var inorder:Function = function (node:BTnode):void
{
a.push(node.nodeData);
}
tree.inorderPrint(inorder);
return a;
}

//判断BST是否包含给定数据, check if the BST contains the given item
public function contains(item:*):Boolean
{
var cursor:BTnode = tree;
var t:int;
while(cursor)
{
t = compare(item, cursor.nodeData)
if(t == 0)
return true;
else
{
cursor = t < 0 ? cursor.leftChild : cursor.rightChild;
}
}
return false;
}

//打印BST结构, print the BST????s frame
public function print():void
{
tree.print(2);
}

//返回BST的信息, return a string representing the BST
public function toString():String
{
return "[BStree, size=" + size + "]";
}
}
}

本文转自
http://www.moorwind.com/read.php?41
### Python 实现自平衡二叉查找树 #### AVL 树的实现 AVL 树是一种高度平衡的二叉搜索树,在任何时刻都保持其高度差不超过1,从而确保了各种操作的时间复杂度为 \(O(\log n)\)[^2]。 ```python class TreeNode: def __init__(self, key): self.key = key self.left = None self.right = None self.height = 1 class AVLTree: def insert(self, root, key): # Perform normal BST insertion if not root: return TreeNode(key) elif key < root.key: root.left = self.insert(root.left, key) else: root.right = self.insert(root.right, key) # Update the height of ancestor node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Get balance factor to check whether this node became unbalanced balance = self.getBalance(root) # If unbalanced, then perform rotations based on cases if balance > 1 and key < root.left.key: return self.rightRotate(root) if balance < -1 and key > root.right.key: return self.leftRotate(root) if balance > 1 and key > root.left.key: root.left = self.leftRotate(root.left) return self.rightRotate(root) if balance < -1 and key < root.right.key: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def delete(self, root, key): # Perform standard BST deletion if not root: return root elif key < root.key: root.left = self.delete(root.left, key) elif key > root.key: root.right = self.delete(root.right, key) else: if root.left is None: temp = root.right root = None return temp elif root.right is None: temp = root.left root = None return temp temp = self.getMinValueNode(root.right) root.key = temp.key root.right = self.delete(root.right, temp.key) if root is None: return root # Update the height of the current node root.height = 1 + max(self.getHeight(root.left), self.getHeight(root.right)) # Check balance and rotate as necessary balance = self.getBalance(root) if balance > 1 and self.getBalance(root.left) >= 0: return self.rightRotate(root) if balance > 1 and self.getBalance(root.left) < 0: root.left = self.leftRotate(root.left) return self.rightRotate(root) if balance < -1 and self.getBalance(root.right) <= 0: return self.leftRotate(root) if balance < -1 and self.getBalance(root.right) > 0: root.right = self.rightRotate(root.right) return self.leftRotate(root) return root def leftRotate(self, z): y = z.right T2 = y.left y.left = z z.right = T2 z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) return y def rightRotate(self, z): y = z.left T3 = y.right y.right = z z.left = T3 z.height = 1 + max(self.getHeight(z.left), self.getHeight(z.right)) y.height = 1 + max(self.getHeight(y.left), self.getHeight(y.right)) return y def getHeight(self, root): if not root: return 0 return root.height def getBalance(self, root): if not root: return 0 return self.getHeight(root.left) - \ self.getHeight(root.right) def preOrder(self, root): if not root: return print("{0} ".format(root.key), end="") self.preOrder(root.left) self.preOrder(root.right) def getMinValueNode(self, root): if root is None or root.left is None: return root return self.getMinValueNode(root.left) def search(root, key): if root is None or root.key == key: return root if key < root.key: return search(root.left, key) return search(root.right, key) ``` 此代码实现了 AVL 树的基本功能,包括插入、删除和查找。通过维护每个节点的高度并计算平衡因子来判断何时需要旋转调整以保持树的平衡性质。 对于红黑树的具体实现较为复杂,涉及到更多颜色标记以及额外的规则用于保证树的特性。由于篇幅原因这里不再展开讨论完整的红黑树实现细节。不过可以确认的是,无论是哪种类型的自平衡二叉查找树,核心目的都是为了避免最坏情况下的线性时间性能问题,即当树变得极度倾斜时的操作效率下降到 O(n)[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值