这就是我在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?
问题:
我在编写递归函数时非常自在,但我似乎仍然感到困惑。
答案 0 :(得分:0)
即使当前节点具有数据,如果它具有左节点,则从该函数返回。理想情况下,这应该是这样的
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.data == value:
return True
if nary_tree(root.left, value):
return True
if nary_tree(root.right, value):
return True
return False #how was this being executed in above example then?