用python打印二叉查找树,带图的
时间: 2023-07-12 15:37:39 浏览: 89
好的,下面是Python代码和二叉查找树图示:
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def insert(root, val):
if not root:
return TreeNode(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val)
return root
def print_tree(root, level=0):
if not root:
return
print_tree(root.right, level=level+1)
print(" "*level + str(root.val))
print_tree(root.left, level=level+1)
# 创建二叉查找树
root = None
values = [5, 3, 7, 1, 4, 6, 8]
for val in values:
root = insert(root, val)
# 打印二叉查找树
print_tree(root)
```
输出结果:
```
8
7
6
5
4
3
1
```
![二叉查找树图示](https://img-blog.csdnimg.cn/20210610095436902.png)
阅读全文