root
node, an empty ArrayList
and an integer nodeData
, write a method that finds a target node - N with data
= nodeData
and populates the ArrayList
with the data
of the ancestor nodes of N - added from the bottom - up.Example:
1
/ \
2 3
/ \ / \
4 5 6 7
Node: 5 ==> [2, 1]
root
is null
, return false
.root.data
is equal to the node
for which the ancestor needs to be found or if printAncestors(root.left, node)
== true
or printAncestors(root.right, node))
== true
then add the data
in the list and return true
. Else return false
.
//Populate the list of ancestors from bottom to top in the below list. public ArrayList<Integer> ancestorsList = new ArrayList<Integer>(); public boolean printAncestors(TreeNode root, int nodeData) { }
C
Java
Python