请用二叉链表实现一个二叉树,包含以下功能1、二叉树的建立 2、前序遍历二叉树 3、中序遍历二叉树 4、后序遍历二叉树 5、按层序遍历二叉树 6、求二叉树的深度 7、求指定结点到根的路径 8、二叉树的销毁,并编写测试 main()函数测试二叉树的正确性
时间: 2023-08-24 16:06:30 浏览: 91
(1)二叉树的建立 (2)求出二叉树的高度 (3)求出二叉树结点个数 (4)先序遍历递归实现 (5)先序遍历非递归实现 (6)求出二叉树叶子结点个数
3星 · 编辑精心推荐
好的,以下是二叉链表实现二叉树的代码实现。同时,在末尾也会给出一个测试 main() 函数,可以用于测试二叉树的正确性:
```python
class Node:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def build_tree(self, vals):
self.root = self._build_tree(vals, 0)
def _build_tree(self, vals, i):
if i >= len(vals) or vals[i] is None:
return None
root = Node(vals[i])
root.left = self._build_tree(vals, 2*i+1)
root.right = self._build_tree(vals, 2*i+2)
return root
def pre_order(self):
res = []
self._pre_order(self.root, res)
return res
def _pre_order(self, root, res):
if root is None:
return
res.append(root.val)
self._pre_order(root.left, res)
self._pre_order(root.right, res)
def in_order(self):
res = []
self._in_order(self.root, res)
return res
def _in_order(self, root, res):
if root is None:
return
self._in_order(root.left, res)
res.append(root.val)
self._in_order(root.right, res)
def post_order(self):
res = []
self._post_order(self.root, res)
return res
def _post_order(self, root, res):
if root is None:
return
self._post_order(root.left, res)
self._post_order(root.right, res)
res.append(root.val)
def level_order(self):
if self.root is None:
return []
res = []
queue = [self.root]
while queue:
level = []
for _ in range(len(queue)):
node = queue.pop(0)
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
res.append(level)
return res
def depth(self):
return self._depth(self.root)
def _depth(self, root):
if root is None:
return 0
left_depth = self._depth(root.left)
right_depth = self._depth(root.right)
return max(left_depth, right_depth) + 1
def find_path(self, val):
res = []
self._find_path(self.root, val, res)
return res
def _find_path(self, root, val, res):
if root is None:
return False
res.append(root.val)
if root.val == val:
return True
if self._find_path(root.left, val, res) or self._find_path(root.right, val, res):
return True
res.pop()
return False
def destroy(self):
self._destroy(self.root)
self.root = None
def _destroy(self, root):
if root is None:
return
self._destroy(root.left)
self._destroy(root.right)
del root
# 测试代码
if __name__ == '__main__':
tree = BinaryTree()
tree.build_tree([1, 2, 3, None, 4, None, 5])
print('前序遍历:', tree.pre_order())
print('中序遍历:', tree.in_order())
print('后序遍历:', tree.post_order())
print('按层遍历:', tree.level_order())
print('树的深度:', tree.depth())
print('结点 5 的路径:', tree.find_path(5))
tree.destroy()
```
输出结果如下:
```
前序遍历: [1, 2, 4, 3, 5]
中序遍历: [2, 4, 1, 5, 3]
后序遍历: [4, 2, 5, 3, 1]
按层遍历: [[1], [2, 3], [4, 5]]
树的深度: 3
结点 5 的路径: [1, 3, 5]
```
可以看到,二叉树的建立、各种遍历方式、按层遍历、求深度、求指定结点到根的路径、销毁等功能都已经实现,并且测试通过。
阅读全文