以特定格式打印二叉树

时间:2016-11-15 05:25:27

标签: python binary-tree

def str_tree(atree,indent_char ='.',indent_delta=2):
    def str_tree_1(indent,atree):
        if atree == None:
            return ''
        else:
            answer = ''
            answer += str_tree_1(indent+indent_delta,atree.right)
            answer += indent*indent_char+str(atree.value)+'\n'
            answer += str_tree_1(indent+indent_delta,atree.left)
            return answer
    return str_tree_1(0,atree) 

def build_balanced_bst(l):
    d = []
    if len(l) == 0:
        return None

    else:
        mid = (len(l)-1)//2
        if mid >= 1:
            d.append(build_balanced_bst(l[:mid]))
            d.append(build_balanced_bst(l[mid:]))
        else:
            return d

build_balanced_bst(l)接受按递增顺序排序的唯一值列表。它返回对均衡二进制搜索树的根的引用。例如,调用build_ballanced_bst(list(irange(1,10))会返回一个高度为3的二叉搜索树,它将打印为:

......10
....9
..8
......7
....6
5
......4
....3
..2
....1

str_tree函数输出build_balanced_bst函数返回的内容

我正在使用build_balanced_bst(l)函数使其适用于str_tree函数。我使用列表中的中间值作为根的值。 但是当我按下面的方式调用函数时:

l = list(irange(1,10))
t = build_balanced_bst(l)
print('Tree is\n',str_tree(t),sep='')

它不会打印任何东西。有人可以帮我修复build_balanced_bst(l)函数吗?

1 个答案:

答案 0 :(得分:1)

保持str_tree方法不变,这是剩下的代码。

class Node:
    """Represents a single node in the tree"""
    def __init__(self, value, left=None, right=None):
        self.value = value
        self.left = left
        self.right = right


def build_balanced_bst(lt):
    """
    Find the middle element in the sorted list
    and make it root.
    Do same for left half and right half recursively.
    """

    if len(lt) == 1:
        return Node(lt[0])
    if len(lt) == 0:
        return None

    mid = (len(lt)-1)//2
    left = build_balanced_bst(lt[:mid])
    right = build_balanced_bst(lt[mid+1:])
    root = Node(lt[mid], left, right)
    return root


ordered_list = list(range(1,11))
bst=build_balanced_bst(ordered_list)
bst_repr = str_tree(bst)
print(bst_repr)

输出结果如下:

......10
....9
..8
......7
....6
5
......4
....3
..2
....1