Add the code to the docs.

This commit is contained in:
Yudong Jin
2022-12-27 19:33:58 +08:00
parent dbb25003ec
commit 449258f0b0
6 changed files with 81 additions and 54 deletions

View File

@ -11,40 +11,34 @@ sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__))))
from include import *
result = []
res = []
""" 前序遍历二叉树 """
""" 前序遍历 """
def pre_order(root: typing.Optional[TreeNode]):
if root is None:
return
# 访问优先级:根结点 -> 左子树 -> 右子树
result.append(root.val)
res.append(root.val)
pre_order(root=root.left)
pre_order(root=root.right)
""" 中序遍历二叉树 """
""" 中序遍历 """
def in_order(root: typing.Optional[TreeNode]):
if root is None:
return
# 访问优先级:左子树 -> 根结点 -> 右子树
in_order(root=root.left)
result.append(root.val)
res.append(root.val)
in_order(root=root.right)
""" 后序遍历二叉树 """
""" 后序遍历 """
def post_order(root: typing.Optional[TreeNode]):
if root is None:
return
# 访问优先级:左子树 -> 右子树 -> 根结点
post_order(root=root.left)
post_order(root=root.right)
result.append(root.val)
res.append(root.val)
""" Driver Code """
@ -56,19 +50,19 @@ if __name__ == "__main__":
print_tree(root)
# 前序遍历
result.clear()
res.clear()
pre_order(root)
print("\n前序遍历的结点打印序列 = ", result)
assert result == [1, 2, 4, 5, 3, 6, 7]
print("\n前序遍历的结点打印序列 = ", res)
assert res == [1, 2, 4, 5, 3, 6, 7]
# 中序遍历
result.clear()
res.clear()
in_order(root)
print("\n中序遍历的结点打印序列 = ", result)
assert result == [4, 2, 5, 1, 6, 3, 7]
print("\n中序遍历的结点打印序列 = ", res)
assert res == [4, 2, 5, 1, 6, 3, 7]
# 后序遍历
result.clear()
res.clear()
post_order(root)
print("\n后序遍历的结点打印序列 = ", result)
assert result == [4, 5, 2, 6, 7, 3, 1]
print("\n后序遍历的结点打印序列 = ", res)
assert res == [4, 5, 2, 6, 7, 3, 1]