07(July) Ancestors in Binary Tree
07. Ancestors in Binary Tree
The problem can be found at the following link: Question Link
Problem Description
Given a Binary Tree and an integer target, find all the ancestors of the given target.
Note:
The ancestor of node x is node y, which is at the upper level of node x, and x is directly connected with node y.
Consider multiple levels of ancestors to solve this problem.
In case there are no ancestors available, return an empty list.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 8
/
7
target = 7Output:
Explanation: The given target is 7. If we go above the level of node 7, then we find 4, 2, and 1. Hence the ancestors of node 7 are 4, 2, and 1.
My Approach
Helper Function:
Define a helper function
findAncestorsto recursively find the ancestors.If the current node is
None, returnFalse.If the current node's data matches the target, return
True.Recursively call
findAncestorsfor the left and right subtrees.If the target is found in either the left or right subtree, add the current node's data to the ancestors list and return
True.
Main Function:
Define the main function
Ancestors.Initialize an empty list
ancestors.Call the helper function with the root and target, passing the ancestors list.
Return the ancestors list.
Time and Auxiliary Space Complexity
Expected Time Complexity: O(n), as we traverse the entire tree to find the target node and its ancestors.
Expected Auxiliary Space Complexity: O(height of tree), as the recursive stack can go up to the height of the tree.
Code
C++
Java
Python
Contribution and Support
For discussions, questions, or doubts related to this solution, feel free to connect on LinkedIn: Any Questions. Let’s make this learning journey more collaborative!
⭐ If you find this helpful, please give this repository a star! ⭐
📍Visitor Count
Last updated