Python数据结构--搜索树 04-看图理解数据结构与算法系列(二叉搜索树)

 1 '''
 2 二叉搜索树(BST)是一棵树,其所有节点都遵循下述属性 - 节点的左子树的键小于或等于其父节点的键。
 3 节点的右子树的键大于其父节点的键。 因此,BST将其所有子树分成两部分; 左边的子树和右边的子树,
 4 可以定义为 -left_subtree (keys)  ≤  node (key)  ≤  right_subtree (keys)
 5 '''
 6 
 7 
 8 class Node:
 9     def __init__(self, data):
10         self.left = None
11         self.right = None
12         self.data = data
13 
14     # 插入节点
15     def insert(self, data):
16         if self.data:
17             if data < self.data:
18                 if self.left is None:
19                     self.left = Node(data)
20                 else:
21                     self.left.insert(data)
22             elif data > self.data:
23                 if self.right is None:
24                     self.right = Node(data)
25                 else:
26                     self.right.insert(data)
27         else:
28             self.data = data
29 
30     # 搜索树方法
31     def findval(self, lkpval):
32         if lkpval < self.data:
33             if self.left is None:
34                 return str(lkpval) + ' Not Found'
35             return self.left.findval(lkpval)
36         elif lkpval > self.data:
37             if self.right is None:
38                 return str(lkpval) + ' Not Found'
39             return self.right.findval(lkpval)
40         else:
41             print(str(self.data) + ' is Found')
42 
43 
44 root = Node(12)
45 root.insert(6)
46 root.insert(14)
47 root.insert(3)
48 print(root.findval(7))
49 print(root.findval(14))

看图更容易理解:https://www.cnblogs.com/Knight-of-Dulcinea/p/9945829.html

04-看图理解数据结构与算法系列(二叉搜索树)

猜你喜欢

转载自www.cnblogs.com/Knight-of-Dulcinea/p/9990995.html
今日推荐