写出二叉树排序查找算法的代码,若查找失败直接插入
时间: 2023-11-19 17:05:59 浏览: 72
好的,下面是二叉树排序查找算法的代码:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
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 not node.left:
node.left = TreeNode(val)
else:
self._insert(val, node.left)
else:
if not node.right:
node.right = TreeNode(val)
else:
self._insert(val, node.right)
def search(self, val):
if not self.root:
self.root = TreeNode(val)
return False
else:
return self._search(val, self.root)
def _search(self, val, node):
if not node:
node = TreeNode(val)
return False
elif val == node.val:
return True
elif val < node.val:
if not node.left:
node.left = TreeNode(val)
return False
else:
return self._search(val, node.left)
else:
if not node.right:
node.right = TreeNode(val)
return False
else:
return self._search(val, node.right)
```
这个二叉树排序查找算法的思路是,先将要插入的元素插入到二叉树中,然后再进行查找。如果查找到了,就返回True;如果查找不到,就直接将要查找的元素插入到二叉树中,然后返回False。
阅读全文