建立一棵用二叉链表方式存储的二叉树,并实现对其进行先序、中序、后序三种方法遍历,输出遍历结果
时间: 2023-06-11 07:09:26 浏览: 114
对所建立的二叉树分别进行先序、中序和后序遍历,并输出结果。
4星 · 用户满意度95%
好的,下面是建立二叉树并遍历的 Python 代码:
```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(self, val_list):
if not val_list:
return None
val = val_list.pop(0)
if not val:
return None
node = Node(val)
node.left = self.build(val_list)
node.right = self.build(val_list)
return node
def preorder(self, node):
if not node:
return
print(node.val, end=" ")
self.preorder(node.left)
self.preorder(node.right)
def inorder(self, node):
if not node:
return
self.inorder(node.left)
print(node.val, end=" ")
self.inorder(node.right)
def postorder(self, node):
if not node:
return
self.postorder(node.left)
self.postorder(node.right)
print(node.val, end=" ")
if __name__ == '__main__':
tree = BinaryTree()
vals = [1, 2, 4, None, None, 5, None, None, 3, 6, None, None, 7, None, None]
tree.root = tree.build(vals)
print("Preorder Traversal:", end=" ")
tree.preorder(tree.root)
print("\nInorder Traversal:", end=" ")
tree.inorder(tree.root)
print("\nPostorder Traversal:", end=" ")
tree.postorder(tree.root)
```
输出结果为:
```
Preorder Traversal: 1 2 4 5 3 6 7
Inorder Traversal: 4 2 5 1 6 3 7
Postorder Traversal: 4 5 2 6 7 3 1
```
以上代码中,我们用 `Node` 类来表示二叉树的节点,包括节点值、左子节点和右子节点。二叉树的构建采用前序遍历的方式,先构建根节点,然后递归构建左子树和右子树。二叉树的遍历采用递归的方式实现,先访问根节点,再递归遍历左子树和右子树。具体来说,先序遍历先访问根节点,中序遍历先访问左子树,后访问根节点,后序遍历先访问左子树和右子树,最后访问根节点。
阅读全文