[問題] 如何在寫recursive function...?

看板Python作者 (Linux & Mac lover)時間15年前 (2009/06/10 15:55), 編輯推噓1(104)
留言5則, 2人參與, 最新討論串1/1
Hi, 小弟我還在初學python的階段 想寫一個binary search tree的程式如下: import bstsize class BST(bstsize.BST): """ Adds select method to BST, starting with code from bstsize. """ def visit(self, node): print "%d\n" % node.key def find_index_node(self, node): if (node.left != None): BST.find_index_node(node.left) BST.visit(node) if (node.right != None): BST.find_index_node(node.right) def select(self, index): """ Takes a 1-based index, and returns the element at that index, or None if the index is out-of-bounds. """ BST.find_index_node(self.root) if __name__ == '__main__': tree = BST() tree.insert(20) tree.insert(10) tree.insert(30) tree.insert(15) tree.insert(25) tree.insert(5) tree.select(1) 當我執行的時候... Traceback (most recent call last): ....(中略) BST.find_index_node(self.root) TypeError: unbound method find_index_node() must be called with BST instance as first argument (got BSTnode instance instead) 我想它的意思是要我加一個instance當它的第一個argument, 可是我要怎麼加呢? 還有這樣的recursive是否有什麼限制? 這樣寫妥當嗎? 資質愚魯,謝謝大家指教 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 99.41.79.238

06/10 15:57, , 1F
PS: 基本上我只是想要作一個in order tree walk而已...
06/10 15:57, 1F

06/10 15:57, , 2F
PS2:import 的module只是一個很基本的tree我就不貼了
06/10 15:57, 2F

06/10 16:23, , 3F
instanceMethod 要用 self.method(...) 呼叫喔
06/10 16:23, 3F

06/10 16:25, , 4F
你寫的 BST.find_index_node() 是 classmethod 的呼叫方式
06/10 16:25, 4F

06/11 00:10, , 5F
Oh...it works..大感謝
06/11 00:10, 5F
文章代碼(AID): #1ABsSDOu (Python)