I know how to find the max depth of a tree using a stack and inorder traversal, but I cannot figure out how to find the min depth of a tree (not necessarily a BST) using a stack or queue instead of recursive calls.
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
One thing to note here is that when you perform recursion you are using your process execution stack. This generally has some limit set by OS. So with each recursion the process state is pushed onto this stack. So at some point stackoverflow occurs.
If you end up doing a iterative version as apposed to recursive, note that the difference here is that this stack implementation is maintained by you. There is lot more work involved but stackoverflow is averted…
We could do something like the following (recursive version)-
MIN-VALUE
Alternatively you could use min-heap which gives you minimum value in constant time.
UPDATE: Since you changed your question to min-depth
MIN-DEPTH
PS: Code is typed freehand, there might be syntactical errors but I believe logic is fine…