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!
So the Longest balanced-path from root to leaf is shorter than the double of the mean length '< 2 * ln(N + 1) + 1'.
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.
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.
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:
Repeat while the queue is not empty, and no result was found:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With