目录
遍历的方式
二元树的遍历顺序,理论上总共四种 ── 但是事实上还是只有 DFS 与 BFS 两种,只不过更动了节点的输出顺序。
注意树根的位置,就能轻松解读这四种序。
Python 实现
Depth-first traversal
1. In-order traversal and infix notation
def inorder(self, root_node):
current = root_node
if current is None:
return
self.inorder(current.left_child)
print(current.data)
self.inorder(current.right_child
2. Pre-order traversal and prefix notation
def preorder(self, root_node):
current = root_node
if current is None:
return
print(current.data)
self.preorder(current.left_child)
self.preorder(current.right_child)
3. Post-order traversal and postfix notation
def postorder(self, root_node):
current = root_node
if current is None:
return
self.postorder(current.left_child)
self.postorder(current.right_child)
print(current.data)
Breadth-first traversal
from collections import deque
class Tree:
def breadth_first_traversal(self):
list_of_nodes = []
traversal_queue = deque([self.root_node])
while len(traversal_queue) > 0:
node = traversal_queue.popleft()
list_of_nodes.append(node.data)
if node.left_child:
traversal_queue.append(node.left_child)
if node.right_child:
traversal_queue.append(node.right_child)
return list_of_nodes