Leaf to Root Path Java


Leaf to Root Path Java
I have been searching around but can't seem to understand how to return path from leaf to root.
For Example:
A
/
B C
/ /
D E F
So if I do A.find(E)
it should return [A,C,E]
and if I do B.find(D)
it should return [B,D]
A.find(E)
[A,C,E]
B.find(D)
[B,D]
My attempt :
// Base Case - The root of this Tree is c. Route is just [child]
public List<Person> find(Person c)
List<Person> path = new ArrayList<Person>();
Person p = c;
while(c != null)
path.add(p);
return path;
This question is a bit unclear: you ask
I... can't seem to understand how to return path from leaf to root.
, but then you say the find()
implementation should return the path from a leaf to a lower leaf. I'm confused on whether you're trying to find elements in both directions, or only children like the examples indicate.– Graham
3 mins ago
I... can't seem to understand how to return path from leaf to root.
find()
Like the example. find() is just a name I called it could be anything.
– It'sME
1 min ago
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
If you want to get to the root you need: while (node.parent != null) node = node.parent thats it
– yossico
9 mins ago