2022-12-20 15:52:00 +08:00
|
|
|
"""
|
2022-11-25 02:04:38 +08:00
|
|
|
File: binary_tree_dfs.py
|
2022-12-27 18:34:12 +08:00
|
|
|
Created Time: 2022-12-20
|
|
|
|
Author: a16su (lpluls001@gmail.com)
|
2022-12-20 15:52:00 +08:00
|
|
|
"""
|
2022-11-25 02:04:38 +08:00
|
|
|
|
|
|
|
import sys, os.path as osp
|
2022-12-27 18:34:12 +08:00
|
|
|
import typing
|
|
|
|
|
2022-11-25 02:04:38 +08:00
|
|
|
sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
|
|
|
|
from include import *
|
|
|
|
|
2022-12-20 15:52:00 +08:00
|
|
|
|
2022-12-27 19:33:58 +08:00
|
|
|
res = []
|
2022-12-20 15:52:00 +08:00
|
|
|
|
2022-12-27 19:33:58 +08:00
|
|
|
""" 前序遍历 """
|
2022-12-27 18:34:12 +08:00
|
|
|
def pre_order(root: typing.Optional[TreeNode]):
|
2022-12-20 15:52:00 +08:00
|
|
|
if root is None:
|
|
|
|
return
|
|
|
|
# 访问优先级:根结点 -> 左子树 -> 右子树
|
2022-12-27 19:33:58 +08:00
|
|
|
res.append(root.val)
|
2022-12-27 18:34:12 +08:00
|
|
|
pre_order(root=root.left)
|
|
|
|
pre_order(root=root.right)
|
|
|
|
|
2022-12-27 19:33:58 +08:00
|
|
|
""" 中序遍历 """
|
2022-12-27 18:34:12 +08:00
|
|
|
def in_order(root: typing.Optional[TreeNode]):
|
2022-12-20 15:52:00 +08:00
|
|
|
if root is None:
|
|
|
|
return
|
|
|
|
# 访问优先级:左子树 -> 根结点 -> 右子树
|
2022-12-27 18:34:12 +08:00
|
|
|
in_order(root=root.left)
|
2022-12-27 19:33:58 +08:00
|
|
|
res.append(root.val)
|
2022-12-27 18:34:12 +08:00
|
|
|
in_order(root=root.right)
|
|
|
|
|
2022-12-27 19:33:58 +08:00
|
|
|
""" 后序遍历 """
|
2022-12-27 18:34:12 +08:00
|
|
|
def post_order(root: typing.Optional[TreeNode]):
|
2022-12-20 15:52:00 +08:00
|
|
|
if root is None:
|
|
|
|
return
|
|
|
|
# 访问优先级:左子树 -> 右子树 -> 根结点
|
2022-12-27 18:34:12 +08:00
|
|
|
post_order(root=root.left)
|
|
|
|
post_order(root=root.right)
|
2022-12-27 19:33:58 +08:00
|
|
|
res.append(root.val)
|
2022-12-20 15:52:00 +08:00
|
|
|
|
|
|
|
|
|
|
|
""" Driver Code """
|
|
|
|
if __name__ == "__main__":
|
|
|
|
# 初始化二叉树
|
|
|
|
# 这里借助了一个从数组直接生成二叉树的函数
|
2023-01-08 19:03:22 +08:00
|
|
|
root = list_to_tree(arr=[1, 2, 3, 4, 5, 6, 7])
|
2022-12-20 15:52:00 +08:00
|
|
|
print("\n初始化二叉树\n")
|
|
|
|
print_tree(root)
|
|
|
|
|
|
|
|
# 前序遍历
|
2022-12-27 19:33:58 +08:00
|
|
|
res.clear()
|
2022-12-27 18:34:12 +08:00
|
|
|
pre_order(root)
|
2022-12-27 19:33:58 +08:00
|
|
|
print("\n前序遍历的结点打印序列 = ", res)
|
|
|
|
assert res == [1, 2, 4, 5, 3, 6, 7]
|
2022-12-20 15:52:00 +08:00
|
|
|
|
|
|
|
# 中序遍历
|
2022-12-27 19:33:58 +08:00
|
|
|
res.clear()
|
2022-12-27 18:34:12 +08:00
|
|
|
in_order(root)
|
2022-12-27 19:33:58 +08:00
|
|
|
print("\n中序遍历的结点打印序列 = ", res)
|
|
|
|
assert res == [4, 2, 5, 1, 6, 3, 7]
|
2022-12-20 15:52:00 +08:00
|
|
|
|
|
|
|
# 后序遍历
|
2022-12-27 19:33:58 +08:00
|
|
|
res.clear()
|
2022-12-27 18:34:12 +08:00
|
|
|
post_order(root)
|
2022-12-27 19:33:58 +08:00
|
|
|
print("\n后序遍历的结点打印序列 = ", res)
|
|
|
|
assert res == [4, 5, 2, 6, 7, 3, 1]
|