Given a binary tree (not a binary search tree), write an algorithm that returns or prints the path from the root to a given target node. The path is represented as a list of node values.
Input: Binary Tree:10/\2030/40 Target Node:40 Output:[10,20,40] Explanation: The path starts from the root(10), goes to node(20), and ends at the node(40).
classSolution {
private List<Integer> path;
publicSolution() {
this.path=new ArrayList<>();
}
public List<Integer>findPath(TreeNode root, int target) {
path.clear();
dfs(root, target);
return path;
}
privatebooleandfs(TreeNode node, int target) {
if (node ==null) {
returnfalse;
}
// Add the current node to the path path.add(node.val);
// Check if this is the target nodeif (node.val== target) {
returntrue;
}
// Recursively search in left and right subtreesif (dfs(node.left, target) || dfs(node.right, target)) {
returntrue;
}
// Backtrack if the target is not in this branch path.remove(path.size() - 1);
returnfalse;
}
}
classSolution:
def __init__(self):
self.path = []
deffindPath(self, root, target):
defdfs(node, target):
ifnot node:
returnFalse# Append the current node to the path self.path.append(node.val)
# Check if this is the target nodeif node.val == target:
returnTrue# Recursively search in left and right subtreesif dfs(node.left, target) or dfs(node.right, target):
returnTrue# Backtrack if the target is not in this branch self.path.pop()
returnFalse# Clear the path for each new search self.path = []
dfs(root, target)
return self.path