1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63
| class TreeNode(): def __init__(self,x): self.left_child=None self.right_child=None self.data=x
class Tree():
def __init__(self,x): self.tree_data=[] self.root=None
def insert(self,root,x): """ 构造二叉查找树 """ if root is None: return TreeNode(x) if root.data > x: root.left_child=self.insert(root.left_child,x) else: root.right_child=self.insert(root.right_child,x) return root
def preorder(slef,root): “”“ 先序遍历 ”“” if not root : return self.tree_data.append(root.data) self.preorder(root.left_child) self.preorder(root.right_child)
def inorder(slef,root): “”“ 中序遍历 ”“” if not root : return self.inorder(root.left_child) self.tree_data.append(root.data) self.inorder(root.right_child)
def postorder(slef,root): “”“ 后序遍历 ”“” if not root : return self.postorder(root.left_child) self.postorder(root.right_child) self.tree_data.append(root.data)
def insert2(self,root,x): """ 构建平衡二叉树 """ if root is None: return TreeNode(x)
tree_node=[root] wile True: node=tree_node.pop(0) if node.left_child is None: node.left_child=TreeNode(x) return root elif node.right_child is None: node.right_child=TreeNode(x) return root else: tree_node.append(node.left_child) tree_node.append(node.right_child)
|