排序二叉树的实现
# coding:utf8 class Node(): def __init__(self, _item): self.item = _item self.left = None self.right = None class SortTree(): def __init__(self): self.root = None def add(self, _item): node = Node(_item) cur = self.root # 如果插入的第一个元素为根节点 if cur == None: self.root = node return # 如果插入元素是叶子节点 while True: ##往左插入 if _item < cur.item: if cur.left == None: cur.left = node break else: cur = cur.left ##往右插入 else: if cur.right == None: cur.right = node break else: cur = cur.right # 深度优先搜索遍历 def forward(self, root): # 前序遍历 :根左右 if root == None: return print(root.item) self.forward(root.left) self.forward(root.right) def middle(self, root): # 中序遍历 :左根右 if root == None: return self.middle(root.left) print(root.item) self.middle(root.right) def back(self, root): # 后序遍历 :左右根 if root == None: return self.back(root.left) self.back(root.right) print(root.item) if __name__ == "__main__": tree = SortTree() alist = [3, 8, 5, 7, 6, 2, 9, 4, 1] for i in alist: tree.add(i) tree.forward(tree.root) tree.middle(tree.root) tree.back(tree.root)
由打印结果可得:中序遍历得到的是排序后的结果。