二叉搜索树(python)

# -*- coding: utf-8 -*-

class BSTNode(object):
    def __init__(self, key, value, left=None, right=None):
        self.key, self.value, self.left, self.right = key, value, left, right

class BST(object):
    def __init__(self, root=None):
        self.root = root

    @classmethod
    def build_from(cls, node_list):
        cls.size = 0
        key_to_node_dict = {}
        for node_dict in node_list:
            key = node_dict[‘key‘]
            key_to_node_dict[key] = BSTNode(key, value=key)  

        for node_dict in node_list:
            key = node_dict[‘key‘]
            node = key_to_node_dict[key]
            if node_dict[‘is_root‘]:
                root = node
            node.left = key_to_node_dict.get(node_dict[‘left‘])
            node.right = key_to_node_dict.get(node_dict[‘right‘])
            cls.size += 1
        return cls(root)

    def _bst_search(self, subtree, key):
        if subtree is None:   # 没找到
            return None
        elif key < subtree.key:
            return self._bst_search(subtree.left, key)
        elif key > subtree.key:
            return self._bst_search(subtree.right, key)
        else:
            return subtree

    def __contains__(self, key):
        """实现 in 操作符"""
        return self._bst_search(self.root, key) is not None

    def get(self, key, default=None):
        node = self._bst_search(self.root, key)
        if node is None:
            return default
        else:
            return node.value

    def _bst_min_node(self, subtree):
        if subtree is None:
            return None
        elif subtree.left is None:   # 找到左子树的头
            return subtree
        else:
            return self._bst_min_node(subtree.left)

    def bst_min(self):
        node = self._bst_min_node(self.root)
        return node.value if node else None

    def _bst_insert(self, subtree, key, value):
        """ 插入并且返回根节点

        :param subtree:
        :param key:
        :param value:
        """
        if subtree is None:   # 插入的节点一定是根节点,包括 root 为空的情况
            subtree = BSTNode(key, value)
        elif key < subtree.key:
            subtree.left = self._bst_insert(subtree.left, key, value)
        elif key > subtree.key:
            subtree.right = self._bst_insert(subtree.right, key, value)
        return subtree

    def add(self, key, value):
        node = self._bst_search(self.root, key)
        if node is not None:   # 更新已经存在的 key
            node.value = value
            return False
        else:
            self.root = self._bst_insert(self.root, key, value)
            self.size += 1
            return True

    def _bst_remove(self, subtree, key):
        """删除节点并返回根节点"""
        if subtree is None:
            return None
        elif key < subtree.key:
            subtree.left = self._bst_remove(subtree.left, key)
            return subtree
        elif key > subtree.key:
            subtree.right = self._bst_remove(subtree.right, key)
            return subtree
        else:
            if subtree.left is None and subtree.right is None:
                return None
            elif subtree.left is None or subtree.right is None:
                if subtree.left is not None:
                    return subtree.left
                else:
                    return subtree.right
            else:
                successor_node = self._bst_min_node(subtree.right)
                subtree.key, subtree.value = successor_node.key, successor_node.value
                subtree.right = self._bst_remove(subtree.right, successor_node.key)
                return subtree

    def remove(self, key):
        assert key in self
        self.size -= 1
        return self._bst_remove(self.root, key)

NODE_LIST = [
    {‘key‘: 60, ‘left‘: 12, ‘right‘: 90, ‘is_root‘: True},
    {‘key‘: 12, ‘left‘: 4, ‘right‘: 41, ‘is_root‘: False},
    {‘key‘: 4, ‘left‘: 1, ‘right‘: None, ‘is_root‘: False},
    {‘key‘: 1, ‘left‘: None, ‘right‘: None, ‘is_root‘: False},
    {‘key‘: 41, ‘left‘: 29, ‘right‘: None, ‘is_root‘: False},
    {‘key‘: 29, ‘left‘: 23, ‘right‘: 37, ‘is_root‘: False},
    {‘key‘: 23, ‘left‘: None, ‘right‘: None, ‘is_root‘: False},
    {‘key‘: 37, ‘left‘: None, ‘right‘: None, ‘is_root‘: False},
    {‘key‘: 90, ‘left‘: 71, ‘right‘: 100, ‘is_root‘: False},
    {‘key‘: 71, ‘left‘: None, ‘right‘: 84, ‘is_root‘: False},
    {‘key‘: 100, ‘left‘: None, ‘right‘: None, ‘is_root‘: False},
    {‘key‘: 84, ‘left‘: None, ‘right‘: None, ‘is_root‘: False},
]

def test_bst_tree():
    bst = BST.build_from(NODE_LIST)
    for node_dict in NODE_LIST:
        key = node_dict[‘key‘]
        assert bst.get(key) == key
    assert bst.size == len(NODE_LIST)
    assert bst.get(-1) is None    

    assert bst.bst_min() == 1

    bst.add(0, 0)
    assert bst.bst_min() == 0

    bst.remove(12)
    assert bst.get(12) is None

    bst.remove(1)
    assert bst.get(1) is None

    bst.remove(29)
    assert bst.get(29) is None

原文地址:https://www.cnblogs.com/muzinan110/p/11167102.html

时间: 2024-10-08 05:21:39

二叉搜索树(python)的相关文章

小白专场-是否同一颗二叉搜索树-python语言实现

目录 一.二叉搜索树的相同判断 二.问题引入 三.举例分析 四.方法探讨 4.1 中序遍历 4.2 层序遍历 4.3 先序遍历 4.4 后序遍历 五.总结 六.代码实现 更新.更全的<数据结构与算法>的更新网站,更有python.go.人工智能教学等着你:https://www.cnblogs.com/nickchen121/p/11407287.html 一.二叉搜索树的相同判断 二叉搜索树是一种特殊的二叉树,在一定程度上是基于二分查找思想产生的,在它的任何一个节点node处,node的左子

不同的二叉搜索树-python

https://leetcode-cn.com/problems/unique-binary-search-trees/ 思路:对于n个数,1,2,3,4,,,,i,,,n.以i为节点时,i前面的序列作为左子,i右边的作为右子树.左右子树时有顺序的,因此可以忽略具体值得大小,只需要看序列的个数.假设长度为n的序列的有F(n)种构造个数,那么以第i个节点为跟节点的时候个数为前后两个新的序列能够构造的个数的乘积.即F(i,n)=F(i-1)F(n-i),所以总个数为: $F(n) = \sum_{i

用Python实现数据结构之二叉搜索树

二叉搜索树 二叉搜索树是一种特殊的二叉树,它的特点是: 对于任意一个节点p,存储在p的左子树的中的所有节点中的值都小于p中的值 对于任意一个节点p,存储在p的右子树的中的所有节点中的值都大于p中的值 一个图例: 基于二叉搜索树的这种关系,我们可以用它来实现有序映射 遍历二叉搜索树 基于二叉搜索树的特性,采用中序遍历的方式可以使得遍历结果是按照从小到大的顺序排列的.了解中序遍历可以参考用Python实现数据结构之树 这里还需要思考的一个内容是在基于中序遍历的前提下,如何求一个节点的后继节点或前驱节

二叉搜索树(BST)---python实现

github:代码实现 本文算法均使用python3实现 1. 二叉搜索树定义 ??二叉搜索树(Binary Search Tree),又名二叉排序树(Binary Sort Tree). ??二叉搜索树是具有有以下性质的二叉树: ??(1)若左子树不为空,则左子树上所有节点的值均小于或等于它的根节点的值. ??(2)若右子树不为空,则右子树上所有节点的值均大于或等于它的根节点的值. ??(3)左.右子树也分别为二叉搜索树. 2. 二叉搜索树的相关操作 2.1 插入操作 ??从根节点开始,若插入

剑指offer python版 二叉搜索树与双向链表

from collections import deque class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Tree(object): """ 非二叉搜索树,建树的时候values中的顺序需要注意 之后有时间会改成二叉搜索树 """ def __init__(self): self.root =

判断一棵树是否为二叉搜索树(二叉排序树) python

输入一棵树,判断这棵树是否为二叉搜索树.首先要知道什么是排序二叉树,二叉排序树是这样定义的,二叉排序树或者是一棵空树,或者是具有下列性质的二叉树: (1)若左子树不空,则左子树上所有结点的值均小于它的根结点的值: (2)若右子树不空,则右子树上所有结点的值均大于它的根结点的值: (3)左.右子树也分别为二叉排序树: (4)没有键值相等的节点 #方法1,直接判断 直接判断的关键在于不能只是单纯地判断根.左.右三个节点的大小关系,左子树的右节点不仅要大于父节点,还要小于父节点的父节点,右子树的左节点

python 二叉搜索树相关代码

class TreeNode: def __init__(self, val): self.val = val self.left = None self.right = None class OperationTree: def insert(self, root, val): if root is None: root = TreeNode(val) elif val < root.val: root.left = self.insert(root.left, val) elif val >

62.二叉搜索树的第k个节点(python)

题目描述 给定一棵二叉搜索树,请找出其中的第k小的结点.例如, (5,3,7,2,4,6,8)    中,按结点数值大小顺序第三小结点的值为4. 思路:中序遍历 1 class Solution: 2 # 返回对应节点TreeNode 3 def KthNode(self, pRoot, k): 4 # write code here 5 stack = [] 6 while stack or pRoot: 7 if pRoot: 8 stack.append(pRoot) 9 pRoot =

[LeetCode] 255. Verify Preorder Sequence in Binary Search Tree 验证二叉搜索树的先序序列

Given an array of numbers, verify whether it is the correct preorder traversal sequence of a binary search tree. You may assume each number in the sequence is unique. Follow up:Could you do it using only constant space complexity? 给一个数组,验证是否为一个二叉搜索树的