我想实现的二叉树是类似5 4 6 - - - 7 - - - - - - - 9 的效果
时间: 2024-01-12 11:02:36 浏览: 41
您可以尝试使用以下代码来构建您想要的二叉树结构:
```python
root = Node(5)
root.left = Node(4)
root.right = Node(6)
root.left.left = Node(None)
root.left.right = Node(None)
root.right.left = Node(None)
root.right.right = Node(7)
root.right.right.left = Node(None)
root.right.right.right = Node(9)
```
这里我们将空节点的值设置为 `None`。如果您想要打印出这个二叉树的结构,可以使用以下代码:
```python
def print_tree(root):
if root is None:
return
# 打印当前节点的值
print(root.data, end=' ')
# 打印左子树结构
if root.left is not None:
print_tree(root.left)
else:
print('-', end=' ')
# 打印右子树结构
if root.right is not None:
print_tree(root.right)
else:
print('-', end=' ')
# 测试代码
root = Node(5)
root.left = Node(4)
root.right = Node(6)
root.left.left = Node(None)
root.left.right = Node(None)
root.right.left = Node(None)
root.right.right = Node(7)
root.right.right.left = Node(None)
root.right.right.right = Node(9)
print_tree(root)
```
运行后的输出结果应该为:
```
5 4 6 - - - 7 - - - - - - - 9 - - -
```
其中 "-" 代表空节点。