From a0f0207bcb4519ded43dcc7d568ab7769eacf4f2 Mon Sep 17 00:00:00 2001 From: dragon <858570636@qq.com> Date: Sat, 17 Nov 2018 16:26:57 -0800 Subject: [PATCH] =?UTF-8?q?24=20|=20=E4=BA=8C=E5=8F=89=E6=A0=91=E5=9F=BA?= =?UTF-8?q?=E7=A1=80=EF=BC=88=E4=B8=8B=EF=BC=89=EF=BC=9A=E6=9C=89=E4=BA=86?= =?UTF-8?q?=E5=A6=82=E6=AD=A4=E9=AB=98=E6=95=88=E7=9A=84=E6=95=A3=E5=88=97?= =?UTF-8?q?=E8=A1=A8=EF=BC=8C=E4=B8=BA=E4=BB=80=20=E4=B9=88=E8=BF=98?= =?UTF-8?q?=E9=9C=80=E8=A6=81=E4=BA=8C=E5=8F=89=E6=A0=91=EF=BC=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- algorithm/tree/bstree.py | 84 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 84 insertions(+) create mode 100644 algorithm/tree/bstree.py diff --git a/algorithm/tree/bstree.py b/algorithm/tree/bstree.py new file mode 100644 index 0000000..39449b2 --- /dev/null +++ b/algorithm/tree/bstree.py @@ -0,0 +1,84 @@ +from btree import Tree + + +class BinarySearchTree(object): + def __init__(self, base): + self.base = base + + def find(self, data): + ''' + 查找 + ''' + p = self.base + while p and p.data != data: + p = p.ltree if p.data > data else p.rtree + return p + + def insert(self, data): + ''' + 插入 + ''' + if not self.base: + self.base = Tree(data=data) + return + pp = None + p = self.base + while p: + pp = p + p = p.ltree if p.data > data else p.rtree + new_p = Tree(data=data) + if pp.data > data: + pp.ltree = new_p + else: + pp.rtree = new_p + + def delete(self, data): + ''' + 删除 + ''' + p = self.base + pp = None + while p and (p.data != data): + pp = p + p = p.ltree if p.data > data else p.rtree + if not p: return + + if p.ltree and p.rtree: + successor = p.rtree + successor_pp = p + while successor.ltree: + successor_pp = successor + successor = successor.ltree + p.data = successor.da + pp, p = successor_pp, successor + + child = p.ltree if p.ltree else p.rtree + if not pp: + self.base = child + elif pp.ltree == p: + pp.ltree = p + else: + pp.rtree = child + + +if __name__ == '__main__': + tree = Tree(data=3) + bst = BinarySearchTree(tree) + bst.insert(3) + bst.insert(4) + bst.insert(5) + bst.insert(8) + bst.insert(10) + bst.insert(13) + bst.insert(33) + bst.insert(44) + bst.insert(1) + bst.insert(2) + target = bst.find(8) + print("--------------------") + print(target.data) + print(target.ltree) + print(target.rtree.data) + print("++++++++++++++++++++") + bst.delete(8) + print(bst.find(8))