Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shortest Root to Leaf Path

What is the easiest way, preferably using recursion, to find the shortest root-to-leaf path in a BST (Binary Search Tree). Java prefered, pseudocode okay.

Thanks!

like image 407
Sev Avatar asked Sep 22 '08 01:09

Sev


People also ask

What is the length of the longest possible path from the root node to a leaf node?

So the Longest balanced-path from root to leaf is shorter than the double of the mean length '< 2 * ln(N + 1) + 1'.

What is minimum depth of a tree?

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum height of below Binary Tree is 2.

How would you check if a path from the root node to a leaf node amounts to a certain value?

Try It! Follow the given steps to solve the problem using the above approach: Recursively move to the left and right subtree and at each call decrease the sum by the value of the current node. If at any level the current node is a leaf node and the remaining sum is equal to zero then return true.


1 Answers

General description:

Use a Breadth-first search (BFS) as opposed to a Depth-first search (DFS). Find the first node with no children.

Using a DFS you might get lucky on some input trees (but there is no way to know you got lucky so you still need to search the whole tree), but using the BFS method is much faster and you can find a solution without touching all nodes.

To find the root to leaf path, you could follow the first found childless node all the way back up to the root using the parent reference. If you have no parent reference stored in each node, you can keep track of the parent nodes as you recurse down. If you have your list in reverse order you could push it all on a stack and then pop it off.

Pseudo-code:

The problem is very simple; here is pseudo code to find the smallest length:

  1. Put the root node on the queue.

Repeat while the queue is not empty, and no result was found:

  1. Pull a node from the beginning of the queue and check if it has no children. If it has no children you are done you found the shortest path.
  2. Otherwise push all the children (left, right) onto the queue.

Finding all shortest paths:

To find all shortest paths you can store the depth of the node along with node inside the queue. Then you would continue the algorithm for all nodes in the queue with the same depth.

Alternative:

If instead you decided to use a DFS, you would have to search the entire tree to find the shortest path. But this could be optimized by keeping a value for the shortest so far, and only checking the depth of future nodes up until you find a new shortest, or until you reach the shortest so far. The BFS is a much better solution though.

like image 138
Brian R. Bondy Avatar answered Sep 18 '22 19:09

Brian R. Bondy