I’m interested in writing a preorder traversal code in Java for JavaScript. I’ve been practicing this question on geeksforgeeks:
Check if a given array can represent Preorder Traversal of Binary Search Tree
This is the algorithm they provided:
1) Create an empty stack.
2) Initialize root as INT_MIN.
3) Do following for every element pre[i]
a) If pre[i] is smaller than current root, return false.
b) Keep removing elements from stack while pre[i] is greater
then stack top. Make the last removed item as new root (to
be compared next).
At this point, pre[i] is greater than the removed root
(That is why if we see a smaller element in step a), we
return false)
c) push pre[i] to stack (All elements in stack are in decreasing
order)
I'm struggling to understand the above algorithm because I’m not sure what an empty stack is (possibly an empty array?), INT_MIN
?
If an empty stack is an empty array, what does this statement mean?
Keep removing elements from stack while pre[i] is greater
than stack top. Make the last removed item the new root (to
be compared next).
In summary, I've tried to come up with an algorithm but need help making it more readable since I only know how to code in Javascript.
Could you assist me in improving the readability of the algorithm for the above code?