Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find the nearest leaf node from given node in binary tree

Given a binary tree (not necessarily a binary search tree ) with root node and a particular node, how to find a leaf node which is nearest to the given node ??

Is there any specific algorithm or modification of existing algorithm for this problem ??

like image 783
Santhosh Mohan Avatar asked Feb 04 '26 18:02

Santhosh Mohan


2 Answers

This is a very typical graph traversal problem. You can use Dijkstra's Algorithm to traverse the graph and find the shortest route to a destination.

We use Dijkstra's and not A* in this case because we do not know what our destination is. If you have played Starcraft, this is (almost certainly) what they used for an worker to find the nearest mineral supply or nearest vehicle that needs repaired.

like image 59
Thomas Havlik Avatar answered Feb 09 '26 15:02

Thomas Havlik


Check this link. The idea is to traverse the given tree in preorder and keep track of ancestors in an array. When we reach the given key, we evaluate distance of the closest leaf in subtree rooted with given key. We also traverse all ancestors one by one and find distance of the closest leaf in the subtree rooted with ancestor. We compare all distances and return minimum.

like image 35
jsp Avatar answered Feb 09 '26 15:02

jsp



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!