def __tree2bin2(p, pos=0): if pos >= p.nbchildren: return None b = treeasbin.TreeAsBin(p.children[pos].key) b.child = __tree2bin2(p.children[pos], 0) b.sibling = __tree2bin2(p, pos + 1) return b
def tree2bin(t): b = treeasbin.TreeAsBin(t.key) for i in range(t.nbchildren - 1, -1, -1): c = tree2bin(t.children[i]) c.sibling = b.child b.child = c return b
def treeToTreeAsBin(T): B = treeasbin.TreeAsBin(T.key, None, None) if T.nbchildren != 0: B.child = treeToTreeAsBin(T.children[0]) S = B.child for i in range(1, T.nbchildren): S.sibling = treeToTreeAsBin(T.children[i]) S = S.sibling return B
def tree2TreeAsBin2(T): B = treeasbin.TreeAsBin(T.key, None, None) firstchild = None for i in range(T.nbchildren - 1, -1, -1): C = tree2TreeAsBin2(T.children[i]) C.sibling = firstchild firstchild = C B.child = firstchild return B
def __tree2tab(parent, i): ''' build child #i of parent ''' if i == parent.nbchildren: return None else: child_i = treeasbin.TreeAsBin(parent.children[i].key) child_i.sibling = __tree2tab(parent, i + 1) child_i.child = __tree2tab(parent.children[i], 0) return child_i
def list2bin(s, pos=0, type=int): t = None if pos < len(s) and s[pos] == '(': pos += 1 w = '' while s[pos] not in '()': w += s[pos] pos += 1 t = treeasbin.TreeAsBin(type(w)) t.child, pos = list2bin(s, pos, type) pos += 1 t.sibling, pos = list2bin(s, pos, type) return t, pos
def __list2treeasbin(s, i=0): if i < len(s) and s[i] == '(': i = i + 1 # to pass the '(' key = "" while not (s[i] in "()"): key = key + s[i] i += 1 B = treeasbin.TreeAsBin(int(key)) (B.child, i) = __list2treeasbin(s, i) i = i + 1 # to pass the ')' (B.sibling, i) = __list2treeasbin(s, i) return (B, i) else: return (None, i)
def treeToTAB(T): return treeasbin.TreeAsBin(T.key, __tree2tab(T, 0), None)
def tree2bin2(t): return treeasbin.TreeAsBin(t.key, child=__tree2bin2(t))
def tree2treeasbin_2(T): return treeasbin.TreeAsBin(T.key, __tree2treeasbin(T, 0), None)