树的深度优先遍历包含三种方法,分别是:
- 前序遍历(根左右)
- 中序遍历(左根右)
- 后序遍历(左右根)
区分这三种遍历方式主要看根的位置
而宽度优先的遍历方式主要是用队列,将节点存入,然后递归读取数据
具体实现见下方程序
class TreeNode:
def __init__(self, value):
self.val = value
self.left = None
self.right = None
# 搜索二叉树的建立
def createTree(root, val):
newnode = TreeNode(val)
if root == None:
root = newnode
return root
current = root
while current != None:
back = current
if val < current.val:
current = current.left
else:
current = current.right
if val < back.val:
back.left = newnode
else:
back.right = newnode
return root
# 深度优先之中序遍历
def inorder(root):
if root != None:
inorder(root.left)
print(root.val, end='\t')
inorder(root.right)
# 前序遍历
def preorder(root):
if root != None:
print(root.val, end="\t")
preorder(root.left)
preorder(root.right)
# 后序遍历
def postOrder(root):
if root != None:
postOrder(root.left)
postOrder(root.right)
print(root.val, end="\t")
# 广度优先遍历
def bfs(root):
nodes = [root]
result = []
while nodes:
node = nodes.pop()
result.append(node.val)
if node.left != None:
nodes.insert(0, node.left)
if node.right != None:
nodes.insert(0, node.right)
print(result)
root = None
nodeval = [10, 5, 15, 4, 6, 12, 17]
for val in nodeval:
root = createTree(root, val)
bfs(root)
inorder(root)
输出:
[10, 5, 15, 4, 6, 12, 17]
4 5 6 10 12 15 17
[Finished in 0.1s]