实现二叉链表创建二叉树(尝试用递归算法实现),并实现先序、中序和后序遍历算法
时间: 2024-05-01 20:03:25 浏览: 109
链表先序建立二叉树,得到中序后序输出,递归和非递归实现(C++代码加设计报告)
5星 · 资源好评率100%
好的,我可以回答这个问题。以下是二叉链表创建二叉树并实现先序、中序和后序遍历算法的递归实现代码:
```python
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
# 创建二叉树
def create_binary_tree(self, lst):
self.root = self._create_binary_tree(lst, 0, len(lst)-1)
def _create_binary_tree(self, lst, left, right):
if left > right:
return None
mid = (left + right) // 2
root = TreeNode(lst[mid])
root.left = self._create_binary_tree(lst, left, mid-1)
root.right = self._create_binary_tree(lst, mid+1, right)
return root
# 先序遍历
def pre_order(self):
res = []
self._pre_order(self.root, res)
return res
def _pre_order(self, node, res):
if node:
res.append(node.val)
self._pre_order(node.left, res)
self._pre_order(node.right, res)
# 中序遍历
def in_order(self):
res = []
self._in_order(self.root, res)
return res
def _in_order(self, node, res):
if node:
self._in_order(node.left, res)
res.append(node.val)
self._in_order(node.right, res)
# 后序遍历
def post_order(self):
res = []
self._post_order(self.root, res)
return res
def _post_order(self, node, res):
if node:
self._post_order(node.left, res)
self._post_order(node.right, res)
res.append(node.val)
```
可以通过以下方式使用以上实现的二叉树类:
```python
tree = BinaryTree()
lst = [1,2,3,4,5,6,7,8,9,10]
tree.create_binary_tree(lst)
print("前序遍历:", tree.pre_order())
print("中序遍历:", tree.in_order())
print("后序遍历:", tree.post_order())
```
输出:
```
前序遍历: [5, 2, 1, 4, 3, 7, 6, 9, 8, 10]
中序遍历: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
后序遍历: [1, 3, 4, 2, 6, 8, 10, 9, 7, 5]
```
阅读全文