在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 教程/ Python/ Python搜索樹
Python樹遍歷算法
Python雙端隊(duì)列
Python隊(duì)列
Python回溯
Python棧
Python數(shù)據(jù)結(jié)構(gòu)開發(fā)環(huán)境
Python數(shù)據(jù)結(jié)構(gòu)簡(jiǎn)介
Python算法分析
Python圖遍歷算法
Python搜索算法
Python圖
Python鏈表
Python集合
Python元組
Python字典
Python矩陣
Python高級(jí)鏈表(雙向鏈表)
Python搜索樹
Python二維數(shù)組
Python堆
Python節(jié)點(diǎn)
Python排序算法
Python數(shù)據(jù)結(jié)構(gòu)
Python遞歸
Python列表
Python數(shù)組
Python算法設(shè)計(jì)
Python哈希表

Python搜索樹

二叉搜索樹(BST)是一棵樹,其所有節(jié)點(diǎn)都遵循下述屬性 - 節(jié)點(diǎn)的左子樹的鍵小于或等于其父節(jié)點(diǎn)的鍵。 節(jié)點(diǎn)的右子樹的鍵大于其父節(jié)點(diǎn)的鍵。 因此,BST將其所有子樹分成兩部分; 左邊的子樹和右邊的子樹,可以定義為 -

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

在B樹搜索的值

在樹中搜索值涉及比較輸入值與退出節(jié)點(diǎn)的值。 在這里,也從左到右遍歷節(jié)點(diǎn),最后是父節(jié)點(diǎn)。 如果搜索到的值與任何退出值都不匹配,則返回未找到的消息,否則返回找到的消息。

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))

執(zhí)行上面示例代碼,得到以下結(jié)果 -

7 Not Found
14 is found
None