关联式容器-BinaryTree

树时一种基础的数据结构,BinaryTree是其中最简单的非平衡二叉树,只定义了一种父-子关系

更常用的是有结构的树:AVL树、红黑树、TRIE树,各种堆

树往往要比python内置的dict类慢一些,python的dict采用和hash表,详见《Python源码剖析》阅读笔记:第五章-dict对象

简单二叉树的代码实现

class BinaryTreeNode:
    def __init__(self,data,left,right):
        self.left = left
        self.data = data
        self.right = right
class BinaryTree:
    def __init__(self):
        self.root = None
    def makeTree(self,data,left,right):
        self.root = BinaryTreeNode(data,left,right)
    def isEmpty(self):
        if self.root is None:
            return True
        else:
            return False
    def preOrder(self,r):
        if r.root is not None:
            print(r.root.data)
            if r.root.left is not None:
                self.preOrder(r.root.left)
            if r.root.right is not None:
                self.preOrder(r.root.right)
    def inOrder(self,r):
        if r.root is not None:
            if r.root.left is not None:
                self.inOrder(r.root.left)
            print(r.root.data)
            if r.root.right is not None:
                self.inOrder(r.root.right)
    def postOrder(self,r):
        if r.root is not None:
            if r.root.left is not None:
                self.preOrder(r.root.left)
            if r.root.right is not None:
                self.preOrder(r.root.right)
            print(r.root.data)