擅长:python、mysql、java
<p>如果您有一个<code>binarytree</code>,您可以简单地找到从根节点到该节点的路径</p>
<pre><code>def hasPath(root, arr, x):
if (not root):
return False
arr.append(root.data)
if (root.data == x):
return True
if (hasPath(root.left, arr, x) or
hasPath(root.right, arr, x)):
return True
arr.pop(-1)
return False
def printPath(root, x):
# vector to store the path
arr = []
if (hasPath(root, arr, x)):
for i in range(len(arr) - 1):
print(arr[i], end = "/")
print(arr[len(arr) - 1])
else:
print("No Path")
</code></pre>