# coding=utf-8 class Node(object): def __init__(self, data=None, left_child=None, right_child=None): self.data = data self.left_child = left_child self.right_child = right_child class BTree(object): def __init__(self): self.root = None def add_node(self, data): node = Node(data) if self.root is None: self.root = node return tmp_queue = [self.root] while True: current_node = tmp_queue.pop(0) if current_node is None: return if current_node.left_child is None: current_node.left_child = node return elif current_node.right_child is None: current_node.right_child = node return tmp_queue.append(current_node.left_child) tmp_queue.append(current_node.right_child) def front_travel(self, node): """先序遍历""" if node is None: return print(node.data) self.front_travel(node.left_child) self.front_travel(node.right_child) def middle_travel(self, node): """中序遍历""" if node is None: return self.middle_travel(node.left_child) print(node.data) self.middle_travel(node.right_child) def last_travel(self, node): """后序遍历""" if node is None: return self.last_travel(node.left_child) self.last_travel(node.right_child) print(node.data) def level_travel(self): """层次遍历""" tmp_queue = [self.root] while True: if len(tmp_queue) == 0: print("travel finish") return current_node = tmp_queue.pop(0) print(current_node.data) if current_node.left_child: tmp_queue.append(current_node.left_child) if current_node.right_child: tmp_queue.append(current_node.right_child) def front(self): """堆栈前序遍历""" if not self.root: return tmp_stack = [] node = self.root while tmp_stack or node: while node: print(node.data) tmp_stack.append(node) node = node.left_child node = tmp_stack.pop() node = node.right_child def middle(self): """堆栈中序遍历""" if not self.root: return tmp_stack = [] node = self.root while tmp_stack or node: while node: tmp_stack.append(node) node = node.left_child node = tmp_stack.pop() print(node.data) node = node.right_child def last(self): """堆栈后序遍历,较难""" if not self.root: return tmp_node = self.root tmp_stack = [] while tmp_node or tmp_stack: while tmp_node: tmp_stack.append(tmp_node) tmp_node = tmp_node.left_child or tmp_node.right_child tmp_node = tmp_stack.pop() print(tmp_node.data) if tmp_stack and tmp_stack[-1].left_child is tmp_node: tmp_node = tmp_stack[-1].right_child else: tmp_node = None if __name__ == "__main__": tree = BTree() for i in range(1, 20): tree.add_node(i) # tree.level_travel() # 广度遍历 # tree.front_travel(tree.root) # 递归前序遍历 # tree.middle_travel(tree.root) # 递归中序遍历 tree.last_travel(tree.root) # 递归后序遍历 print("---" * 20) # tree.front() # 堆栈前序遍历 # tree.middle() # 堆栈中序遍历 tree.last() # 堆栈后序遍历
总结:
总结了一下二叉树的构建和遍历,参考了一下网上其他的博客,有些博客写的很好,但是更多博客的算法要么啰里啰嗦,要么代码质量不高,读起来很费力,所以自己重新写了一遍。其中堆栈后序遍历稍微麻烦一些,有点难理解,建议在纸上画一下图。