它输出无

时间:2019-05-16 12:15:44

标签: python algorithm graph graph-theory breadth-first-search

算法顺序(树)    1.遍历左侧子树,即调用Inorder(left-subtree)    2.访问根。    3.遍历右侧子树,即调用Inorder(right-subtree)

#function to return tree
def buildtree(preorder,inorder,start,end):
    tree=[]
    k=0
    if start > end : 
        return 0


    if start == end: 
        return tree

  #compare bn inorder and preorder 

    for i in range(start,end+1):
        if inorder[i]==preorder[0]:
            k=i
            break
    tree.append(inorder[k])
#recursive function
    buildtree(preorder[1:],inorder,start,k-1)
    buildtree(preorder[1:],inorder,k+1,end)

if __name__ == "__main__": 
    inorder = [4, 2, 5, 1, 3]  
    preorder = [1, 2, 4, 5, 3]  

    len1 = len(inorder) 
    tree = buildtree(preorder, inorder,0, len1-1) 
    print( tree) 

1 个答案:

答案 0 :(得分:0)

向k语言环境分配内容

def buildtree(preorder,inorder,start,end):
  k = 0
  ...

或全局

k = 0 
def buildtree(preorder,inorder,start,end):
  global k