我有一棵数字树。每个节点可以具有左子节点和右子节点。数字不能重复,但它们可以在树上的任何地方。我需要在树上搜索一个数字,然后将它的路径打印到树的根部。
我无法想办法让节点跟踪谁是它的父节点,这样我就可以将它们打印回根节点。我怎么能做到这一点?
代码如下:
# The Tree class holds a value and left and right childs
class Tree:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
# recursive function that searches the tree for a node
# and alerts when the node is found
def searchNode(tree, node):
if tree == None:
return
else:
searchNode(tree.left,node)
searchNode(tree.right,node)
if tree.value == node:
print "Node " + str(node) + " found!"
# manually creating a tree with its subtrees
tree1 = Tree(1,Tree(40,Tree(33,left=Tree(204)),
Tree(21,left=Tree(12,right=Tree(2,left=Tree(32))))),
Tree(7,Tree(46),Tree(11,Tree(3),Tree(1000))))
# searching tree
searchNode(tree1, 46)
答案 0 :(得分:1)
我确信你有理由将树用于O(n)查找而不是O(log n),即不使用二叉搜索树,所以我不会质疑:)
要解决您的问题,您可以向函数添加第三个参数以维护路径。以下是一个非常简单和低效的解决方案。
def searchNode(tree, node, path):
if tree == None:
return
else:
#print tree.value
path.append(tree.value) #add to path because we visited
searchNode(tree.left,node, path)
searchNode(tree.right,node, path)
if tree.value == node:
print "Node " + str(node) + " found!"
print path
else:
path.pop() #remove from path because we are going back
您将使用空路径调用函数:searchNode(tree1, 46, [])
请注意,path
中的值即使在找到元素后也会继续更改,因为没有任何东西阻止您的函数进一步遍历树。您可以通过阻止此操作来提高代码的效率。如果您不想这样做,请在找到节点时将path
中的值复制到其他变量中,以便以后可以使用它。