我有一棵数字树。每个节点可以有一个左子节点和一个右子节点。数字不能重复,但它们可以在树上的任何地方。我需要在树上搜索一个数字,然后打印它到树根的路径。
我想不出办法让节点跟踪谁是它的父节点,所以我可以将它们打印回根目录。我怎么能做到这一点?
代码如下:
# 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)