これは、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 を返しません。そのため、関数にステップインしてデバッグを試みます。値を返すだけで再帰を回避することは想定されていないことに気付きました。一致するノードがある場合、上記のコードはTrue
1 回および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?
質問:
- 私は何を誤解していますか?
- 上記のコードをどのように修正しますか?
私は再帰関数を書くことにかなり慣れてきましたが、まだ混乱しているようです。