0
這是我怎麼會遍歷二叉樹在Python簡單樹遍歷:幫我調試
def binary_tree(root):
if root.left:
binary_tree(root.left)
print root
if root.right:
binary_tree(root.right)
,如果我需要返回通過路徑:
def binary_tree(node, path):
if root.left:
binary_tree(root.left)
path.append(root)
if root.right:
binary_tree(root.right)
return path
好了,很容易的。我對樹遍歷有信心,所以我嘗試以下。
def nary_tree(root, value):
"""return True if there is a node with value exists in root"""
if not root: #empty tree
return False
if root.left:
nary_tree(root.left, value)
if root.data == value: #recurse up until the current node has a right child
return True
if root.right:
nary_tree(root.right, value)
return False
這應該不會返回True。所以我嘗試調試,進入功能。我意識到我不應該通過返回一個值來逃避遞歸。上面的代碼會多次返回True
一次和False
,如果有匹配的節點,我幾乎總是會得到一個False
。所以我嘗試以下方法:
def nary_tree(root, value):
"""return True if there is a node with value exists in root"""
if not root: #empty tree
return False
if root.left:
return nary_tree(root.left, value)
if root.data == value:
#but in this case, this is never executed
return True
if root.right:
return nary_tree(root.right, value)
return False #how was this being executed in above example then?
問題:
- 我是什麼誤會?
- 你會如何解決上面的代碼?
我在編寫遞歸函數時相當舒服,但我似乎仍然感到困惑。
如何,如果nary_tree(root.left,值)實際上在這種情況下工作嗎? –
@MaximusS如果返回'True','if'中的語句將被執行。 – thefourtheye