2016-11-15 265 views
1
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(名單(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

保持原來的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