Given a binary tree and a target node, write a function to print or return all the ancestors of the target node in the binary tree. Ancestors of a node are all the nodes in the path from the root to the parent of the target node.
Input:
Binary Tree:
1/ \
23/ \
45 Target Node: 4 Output: [2, 1]
Explanation:
The ancestors of node 4 are node 2and node 1 (starting from its parent up to the root).
Input: Binary Tree:10/\2030/\4050 Target Node:50 Output:[20,10] Explanation: For target node 50, its ancestors in the binary tree are 20 and 10(parent to root order).
Recursive DFS Traversal: To find the ancestors, traverse the binary tree using Depth First Search (DFS). Start from the root node, and explore its left and right subtrees, looking for the target node.
Tracking Path: When the target node is found, backtrack by storing all nodes encountered during the recursion that led to the target node.
Stopping Condition: Stop when the target node is reached, and return the path of nodes traversed up to this point.
classSolution {
public List<Integer>printAncestors(TreeNode root, int target) {
// List to store ancestors List<Integer> ancestors =new ArrayList<>();
// Helper function for recursive traversalbooleanfindAncestors(TreeNode node, int target, List<Integer> ancestors) {
// Base case: if node is nullif (node ==null) {
returnfalse;
}
// Check if current node is the targetif (node.val== target) {
returntrue;
}
// Recursively search in left and right subtreesif (findAncestors(node.left, target, ancestors) || findAncestors(node.right, target, ancestors)) {
// Add current node (ancestor) to the list ancestors.add(node.val);
returntrue;
}
returnfalse;
}
// Start DFS to find ancestors of the target node findAncestors(root, target, ancestors);
return ancestors;
}
}
classSolution:
defprintAncestors(self, root, target):
deffindAncestors(node, target, ancestors):
# Base case: If node is Noneifnot node:
returnFalse# Check if the current node is the targetif node.val == target:
returnTrue# Recursively check the left and right subtreeif findAncestors(node.left, target, ancestors) or findAncestors(node.right, target, ancestors):
# Add current node (ancestor) to the list ancestors.append(node.val)
returnTruereturnFalse# List to store ancestors ancestors = []
# Start DFS to find ancestors of the target node findAncestors(root, target, ancestors)
return ancestors
⏰ Time complexity: O(n). We traverse all nodes in the tree in the worst case when the target node is a leaf node.
🧺 Space complexity: O(h). The space complexity is determined by the depth of the tree h due to recursive calls (stack frames). In the case of a skewed tree, h = n, making worst-case space complexity O(n).