I am in the process of converting recursive function for a BST to non recursive to help prepare for an interview. So far I figured out preorder, inorder, postorder, search, delete, insert, and converting the BST to a circular linked list. I am having trouble figuring out how to use stack or queues to get the height and to find if it is a BST. Any tips would be greatly appreciated. I am not looking for code but the logic behind the code.
Share
For starters, great job preparing for interviews like this! I hope that you’re having fun playing around with these algorithms.
Let’s begin with the task of trying to determine if the binary tree is a BST. One way of doing this is to do an inorder walk of the tree and check if the elements are in sorted order. This will be true if and only if the tree is a BST. Since you already have code to do an inorder walk of the elements of the tree, you should be able to easily adapt your code to check if the elements that come out of the inorder walk are sorted by keeping track of the last element you saw in the inorder walk, then comparing each element generated to the previous element. If the two are out of order, the tree is not a BST.
To determine the height of the tree, one option would be to take any of the searches that you’ve come up with so far (preorder, postorder, inorder) and keep track of the height of the stack at each point. The idea here is that since your stack will always keep track of the path back from any node up to the root, you can simply walk the tree and record the deepest that you ever saw the stack become. This maximum depth is then the height of the tree.
Hope this helps! And best of luck with interviews!