Code前端首页关于Code前端联系我们

Python 数据结构教程:二叉搜索树 (BST)

terry 2年前 (2023-09-27) 阅读数 89 #数据结构与算法

二叉搜索树 (BST) 是一棵树,其节点都遵循以下属性 - 节点的左子树的键小于或等于它的父节点键。节点右子树的键大于其父节点的键。因此,BST将其所有子树分成两部分;左子树和右子树,可以定义为 -

left_subtree (keys)  ≤  node (key)  ≤  right_subtree (keys)
Python

在 B 树中搜索值

在树中 搜索值涉及将输入值与输出值节点进行比较。这里再次从左到右遍历节点,最后遍历父节点。如果搜索到的值与任何输出值都不匹配,则返回未找到消息,否则返回找到消息。

class Node:

    def __init__(self, data):

        self.left = None
        self.right = None
        self.data = data

# Insert method to create nodes
    def insert(self, data):

        if self.data:
            if data < self.data:
                if self.left is None:
                    self.left = Node(data)
                else:
                    self.left.insert(data)
            elif data > self.data:
                if self.right is None:
                    self.right = Node(data)
                else:
                    self.right.insert(data)
        else:
            self.data = data
# findval method to compare the value with nodes
    def findval(self, lkpval):
        if lkpval < self.data:
            if self.left is None:
                return str(lkpval)+" Not Found"
            return self.left.findval(lkpval)
        elif lkpval > self.data:
            if self.right is None:
                return str(lkpval)+" Not Found"
            return self.right.findval(lkpval)
        else:
            print(str(self.data) + ' is found')
# Print the tree
    def PrintTree(self):
        if self.left:
            self.left.PrintTree()
        print( self.data),
        if self.right:
            self.right.PrintTree()


root = Node(12)
root.insert(6)
root.insert(14)
root.insert(3)
print(root.findval(7))
print(root.findval(14))
Python

执行上面的代码示例,得到以下结果 -

7 Not Found
14 is found
None

版权声明

本文仅代表作者观点,不代表Code前端网立场。
本文系作者Code前端网发表,如需转载,请注明页面地址。

热门