我正在尝试定义3个函数,这些函数将进入一个函数,然后将返回True或False,具体取决于给定列表(树)中是否存在特定的数字(键)。这是我得到的代码:
def is_empty_tree(tree):
return isinstance(tree, list) and not tree
def is_leaf(tree):
return isinstance(tree, int)
def left_subtree(tree):
return tree[0]
def right_subtree(tree):
return tree[2]
def get_key(tree):
return tree[1]
def is_innernode(tree):
return isinstance(tree,list)
def func_traverse(binary_tree, func1, func2, func3):
if is_empty_tree(binary_tree):
return func3()
if is_leaf(binary_tree):
return func2(binary_tree)
if is_innernode(binary_tree):
return func3(get_key(binary_tree), \
traverse(left_subtree(binary_tree), inner_node_fn, leaf_fn, \
empty_tree_fn), traverse(right_subtree(binary_tree), \
inner_node_fn, leaf_fn, empty_tree_fn))
def func3():
return False
def func2(num):
return num
def func3(binary_tree, left, right):
if isinstance(binary_tree, int):
return exists(binary_tree)
else:
????
def contain__the_key(key, binary_tree):
return key == func_traverse(binary_tree, search, exists, not_in_tree)
#Test example
contain_the_key(4, [6, 2, [[4, 3, 9], 0, []]])
>>> True
conatin_the_key(6, [[], 1, 5])
>>> False
问题是我对如何编写func1,func2,func3并没有真正的好主意,因此如果它在列表中,它将返回true,否则返回false。任何想法将不胜感激!