python-树-BST_Traversal-二叉搜索树的遍历

写一个函数,函数的输入是一个二叉搜索树BST和一个array。

函数可以按照要求将便利的结果放进array中,然后进行输出。

有一个树状结构:

							10

							/	\

						5			15

					/		\				\

				2			5				22

			/

		1

遍历方法

中序遍历:[1,2,5,5,10,15,22] 指先访问左(右)子树,然后访问根,最后访问右(左)子树的遍历方式

前序遍历:[10, 5, 2, 1, 5, 15, 22]指先访问根,然后访问子树的遍历方式

后序遍历:[1, 2, 5, 5, 22, 15, 10]指先访问子树,然后访问根的遍历方式

1.1深度优先遍历

def inOrderTraverse(tree, array):
    if tree is not None:
        inOrderTraverse(tree.left,array)
        array.append(tree.value)
        inOrderTraverse(tree.right,array)
    return array


def preOrderTraverse(tree, array):
    if tree is not None:
        array.append(tree.value)
        preOrderTraverse(tree.left,array)
        preOrderTraverse(tree.right,array)
    return array


def postOrderTraverse(tree, array):
    if tree is not None:
        postOrderTraverse(tree.left,array)
        postOrderTraverse(tree.right,array)
        array.append(tree.value)
    return array


class Tree:
    def __init__(self,value = None,left = None,right = None):
        self.value = value
        self.right = right
        self.left = left
node_1 = Tree(value = 10)
node_2 = Tree(value = 5)
node_3 = Tree(value = 15)
node_4 = Tree(value = 2)
node_5 = Tree(value = 5)
node_6 = Tree(value = 22)
node_7 = Tree(value = 1)

node_1.left = node_2
node_1.right = node_3
node_2.left = node_4
node_2.right = node_5
node_3.right = node_6
node_4.left = node_7

array_recorder =[]
print(f"inOrderTraverse: {inOrderTraverse(tree = node_1, array = array_recorder)}")
array_recorder =[]
print(f"preOrderTraverse: {preOrderTraverse(tree = node_1, array = array_recorder)}")
array_recorder =[]
print(f"postOrderTraverse: {postOrderTraverse(tree = node_1, array = array_recorder)}")



### Time: O(n)
### Space: O(n)

输出

inOrderTraverse: [1, 2, 5, 5, 10, 15, 22]
preOrderTraverse: [10, 5, 2, 1, 5, 15, 22]
postOrderTraverse: [1, 2, 5, 5, 22, 15, 10]
[Finished in 0.6s]

Time: O(n)

Space: O(n)

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页