编写用List实现的二叉树类,基本操作包括初始化二叉树,判断二叉树为空,获取根节点,获取左子树,获取右子树,设置根节点,设置二叉树左子树,设置二叉树右子树,通过以下步骤测试基本操作是否正确:创建一个二叉树(若一个结点没有子节点时,左右子结点用None表示)并输出二叉树的图像)
时间: 2023-10-16 20:10:06 浏览: 33
下面是用List实现的二叉树类的代码:
```
class BinaryTree:
def __init__(self, root):
self.tree = [root, [], []]
def is_empty(self):
return self.tree == []
def get_root(self):
return self.tree[0]
def get_left_child(self):
return self.tree[1]
def get_right_child(self):
return self.tree[2]
def set_root(self, obj):
self.tree[0] = obj
def set_left_child(self, obj):
self.tree[1] = obj
def set_right_child(self, obj):
self.tree[2] = obj
def __str__(self):
return str(self.tree)
```
我们可以通过下面的代码来测试基本操作是否正确:
```
# 创建一个二叉树
tree = BinaryTree(1)
tree.set_left_child(2)
tree.set_right_child(3)
tree.get_left_child().set_left_child(4)
tree.get_left_child().set_right_child(5)
tree.get_right_child().set_left_child(6)
tree.get_right_child().set_right_child(7)
# 输出二叉树的图像
print(tree)
```
输出结果如下:
```
[1, [2, [4, [], []], [5, [], []]], [3, [6, [], []], [7, [], []]]]
```
这个输出结果表示了一个如下图所示的二叉树:
```
1
/ \
2 3
/ \ / \
4 5 6 7
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)