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 64 65 66 67 68 69 70 71 72 73
| class Node(object): """节点"""
def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right
class Tree(object): """创建树"""
default_chars = [chr(c) for c in range(65, 91)]
def __init__(self, seq=None, depth=4, is_complete=True): """ 初始化 :param seq: 二叉树元素序列 :param depth: 深度 :param is_complete: 是否为完全二叉树 """ seq = self.default_chars if seq is None else seq if len(seq) < depth and is_complete: raise ParamsError('seq is too small or depth is too large!')
self.depth = depth self._root = None self.chars = seq[:pow(2, self.depth) - 1] if is_complete else seq
def create(self): """执行创建""" for (i, j) in enumerate(self.chars): node = Node(j) if i == 0: self._root = node else: self._insert_node(node)
return self._root
def _recursive_create_node(self, seq): """递归创建节点""" n = len(seq) if n == 0: return None i = n // 2 return Node(seq[i], self._recursive_create_node(seq[:i]), self._recursive_create_node(seq[i + 1:])) def _insert_node(self, node): lst = []
def _insert(tree_node, p, node): if tree_node.left is None: tree_node.left = node lst.append(tree_node.left) return elif tree_node.right is None: tree_node.right = node lst.append(tree_node.right) return else: lst.append(tree_node.left) lst.append(tree_node.right) if p > (len(lst) - 2): return else: _insert(lst[p + 1], p + 1, node)
lst.append(self._root) _insert(self._root, 0, node)
|