# Tree ClassclassTreeNode(object):def__init__(self, data, left =None, right =None):
self.data = data
self.left = left
self.right = right
def__str__(self):returnstr(self.data)# Create a treedefcreateTree():
A, B, C, D, E, F, G, H, I =[TreeNode(_)for _ in"ABCDEFGHI"]
A.left = B
A.right = C
B.right = D
C.left = E
C.right = F
E.left = G
F.left = H
F.right = I
return A
defpreOrder(root):ifnot root:return
result.append(root)
preOrder(root.left)
preOrder(root.right)if __name__ =='__main__':
root = createTree()
result =[]
preOrder(root)for i inrange(len(result)):print(result[i])
中序遍历
# Tree ClassclassTreeNode(object):def__init__(self, data, left =None, right =None):
self.data = data
self.left = left
self.right = right
def__str__(self):returnstr(self.data)# Create a treedefcreateTree():
A, B, C, D, E, F, G, H, I =[TreeNode(_)for _ in"ABCDEFGHI"]
A.left = B
A.right = C
B.right = D
C.left = E
C.right = F
E.left = G
F.left = H
F.right = I
return A
definOrder(root):ifnot root:return
inOrder(root.left)
result.append(root)
inOrder(root.right)if __name__ =='__main__':
root = createTree()
result =[]
inOrder(root)for i inrange(len(result)):print(result[i])
后序遍历
# Tree ClassclassTreeNode(object):def__init__(self, data, left =None, right =None):
self.data = data
self.left = left
self.right = right
def__str__(self):returnstr(self.data)# Create a treedefcreateTree():
A, B, C, D, E, F, G, H, I =[TreeNode(_)for _ in"ABCDEFGHI"]
A.left = B
A.right = C
B.right = D
C.left = E
C.right = F
E.left = G
F.left = H
F.right = I
return A
defpostOrder(root):ifnot root:return
postOrder(root.left)
postOrder(root.right)
result.append(root)if __name__ =='__main__':
root = createTree()
result =[]
postOrder(root)for i inrange(len(result)):print(result[i])
循环实现
前序遍历
# 中左右defpreOrder(root):
node = root
stack =[]
result =[]while node or stack:if node:
result.append(node)
stack.append(node.right)
node = node.left
else:
node = stack.pop()return result
中序遍历
# 左中右definOrder(root):
node = root
stack =[]
result =[]while node or stack:if node:
stack.append(node)
node = node.left
else:
node = stack.pop()
result.append(node)
node = node.right
return result
后序遍历
# 中右左,反转变为左右中defpostOrder(root):
node = root
stack =[]
result =[]while node or stack:if node:
result.append(node)
stack.append(node.left)
node = node.right
else:
node = stack.pop()
result.reverse()return result
层序遍历(用队列实现)
from collections import deque
deflevelOrder(root):
q = deque([root])
result =[]while q:
node = q.popleft()
result.append(node)if node.left:
q.append(node.left)if node.right:
q.append(node.right)for i inrange(len(result)):print(result[i])return result