Welcome to the daily solving of our PROBLEM OF THE DAY with Devashish Khare. We will discuss the entire problem step-by-step and work towards developing an optimized solution. This will not only help you brush up on your concepts of Tree but also build up problem-solving skills.
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.
Examples:
Input:
1
/ \
2 3
target = 2
Output: 1
Explanation: The given target is 2, if we go above the level of node 2, then we find 1 only. Hence the ancestor of node 2 is 1.
Problem Link: https://practice.geeksforgeeks.org/problems/ancestors-in-binary-tree/1