I'm having trouble computing the path from the root to a specified node in a binary tree (this is specifically about a Python solution to this problem).
Here's an example. Given the binary tree below, if I specify the node whose value is 4, I want to return [1, 2, 4]. If I specify the node whose value is 5, I want to return [1, 2, 5].
1
/ \
2 3
/ \
4 5
Here's my attemped solution.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
def path(root, k, l=[]):
if not root:
return []
if root.val == k:
return l
# Pre-order traversal: Visit root, then left, then right.
l.append(root.val)
path(root.left, k, l)
path(root.right, k, l)
return l