From 6a261c80ae4597eb1bbdcfb2d28655c409ab5274 Mon Sep 17 00:00:00 2001 From: Logen <47022821+Logenleedev@users.noreply.github.com> Date: Mon, 26 Dec 2022 10:45:20 -0600 Subject: [PATCH] add tree_DFS python code --- codes/python/chapter_tree/binary_tree_dfs.py | 36 ++++++++++++++++++++ 1 file changed, 36 insertions(+) diff --git a/codes/python/chapter_tree/binary_tree_dfs.py b/codes/python/chapter_tree/binary_tree_dfs.py index 094bd4cb5..425d8c771 100644 --- a/codes/python/chapter_tree/binary_tree_dfs.py +++ b/codes/python/chapter_tree/binary_tree_dfs.py @@ -8,3 +8,39 @@ import sys, os.path as osp sys.path.append(osp.dirname(osp.dirname(osp.abspath(__file__)))) from include import * +# 定义一个result数组用来存储遍历的结果 +result = [] + +# 前序遍历 +def preorder(root): + if root == None: + return [] + · + # 访问顺序:根结点 -> 左子树 -> 右子树 + + result.append(root.val) + preorder(root.left) + preorder(root.right) + + +# 中序遍历 +def inorder(root): + if root == None: + return [] + + # 访问顺序:左子树 -> 根结点 -> 右子树 + + inorder(root.left) + result.append(root.val) + inorder(root.right) + +# 后序遍历 +def postorder(root): + if root == None: + return [] + + # 访问顺序:左子树 -> 右子树 -> 根结点 + + postorder(root.left) + postorder(root.right) + result.append(root.val)