class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class BinarySearchTree:
def __init__(self):
self.root = None
def insert(self, val):
if not self.root:
self.root = TreeNode(val)
else:
self._insert(val, self.root)
def _insert(self, val, node):
if val < node.val:
if node.left:
self._insert(val, node.left)
else:
node.left = TreeNode(val)
else:
if node.right:
self._insert(val, node.right)
else:
node.right = TreeNode(val)
def find(self, val):
if self.root:
return self._find(val, self.root)
else:
return None
def _find(self, val, node):
if val == node.val:
return node
elif val < node.val and node.left:
return self._find(val, node.left)
elif val > node.val and node.right:
return self._find(val, node.right)
else:
return None
bst = BinarySearchTree()
bst.insert(5)
bst.insert(2)
bst.insert(7)
bst.insert(1)
bst.insert(3)
bst.insert(6)
bst.insert(8)
print(bst.find(3).val)
python---数据结构---二叉排序树
最新推荐文章于 2024-11-03 20:27:08 发布