在BST

2015-11-11 40 views
0

獲得下一個最高值,我寫了一個函數在二叉搜索樹,以獲得下一個最高值,並返回0,如果輸入值是樹中最高的:在BST

def getNext(root, x): 
if x > root.d: 
    if root.r == None: 
     return 0 
    else: 
     if x > root.r.d: 
      getNext(root.r, x) 
     else: 
      temp = root.r 

      while temp.l != None: 
       temp = temp.l 

      return temp.d 
else: 
    if root.l == None: 
     return root.d 
    elif x < root.l.d: 
     getNext(root.l, x) 
    else: 
     temp = Node('') 
     temp = root.l.r #53 

     if temp.d > x: 
      getNext(temp, x) 
     else: 
      while temp != None: 
       if temp.r == None: 
        return root.d 
       elif x > temp.r.d: 
        temp = temp.r 
       else: 
        getNext(temp.r, x) 
        break 

但它只返回None

我曾嘗試返回之前添加打印,並且打印輸出實際正確

回答

1

每次遞歸調用之前添加return,即

return getNext(root.r,x)

return getNext(root.l,x)

return getNext(temp,x)

return getNext(temp.r,x)