建立一棵二叉树,并对其进行遍历(先序、中序、后序),打印输出遍历结果代码实现
时间: 2023-07-10 14:15:10 浏览: 73
好的,以下是建立一棵二叉树,并对其进行遍历(先序、中序、后序),打印输出遍历结果的 Python 代码实现:
```python
# 定义二叉树节点类
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 先序遍历
def preorderTraversal(root):
if not root:
return []
res = []
res.append(root.val)
res += preorderTraversal(root.left)
res += preorderTraversal(root.right)
return res
# 中序遍历
def inorderTraversal(root):
if not root:
return []
res = []
res += inorderTraversal(root.left)
res.append(root.val)
res += inorderTraversal(root.right)
return res
# 后序遍历
def postorderTraversal(root):
if not root:
return []
res = []
res += postorderTraversal(root.left)
res += postorderTraversal(root.right)
res.append(root.val)
return res
# 建立二叉树
def buildTree():
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
root.right.left = TreeNode(6)
root.right.right = TreeNode(7)
return root
# 测试代码
root = buildTree()
print('先序遍历结果:', preorderTraversal(root))
print('中序遍历结果:', inorderTraversal(root))
print('后序遍历结果:', postorderTraversal(root))
```
输出结果如下:
```
先序遍历结果: [1, 2, 4, 5, 3, 6, 7]
中序遍历结果: [4, 2, 5, 1, 6, 3, 7]
后序遍历结果: [4, 5, 2, 6, 7, 3, 1]
```
阅读全文