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

							10

/	\

5			15

/		\				\

2			5				22

/

1



### 遍历方法

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]


06-25 2369

06-20 103
10-21 192
10-24 1664
03-02 14
10-23 134