Binary Search Tree - Iterative inorder tree walk
Today, I’ll walk you through an iterative algorithm for inorder tree walk over a Binary search tree. First, let me draw your attention to an exercise in the CLRS book [1].
Exercise 12.1-3
Give a nonrecursive algorithm that performs an inorder tree walk. (Hint: An easy solution uses a stack as an auxiliary data structure. A more complicated, but elegant, solution uses no stack but assumes that we can test two pointers for equality.)
The one which uses a stack is relatively simple. Here’s how it looks.
**Input:** root node of the tree T
INORDER−TREEWALK−ITERATIVE(root)
++ Let s be an empty stack
++ TreeNode current←root
++ `while`!s.isEmpty or current≠sentinel
++ ++ `if` current≠sentinel
++ ++ ++ s.push(current)
++ ++ ++ current←current.left
++ ++ `else`
++ ++ ++ TreeNode r←s.pop()
++ ++ ++ print r
++ ++ ++ current←r.right
Now let’s go ahead and write an iterator that performs an inorder tree walk on our BST.
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
- BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
- boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
- int next() Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
Example 1:
By using the algorithm defined above, let’s implement the iterator.
class BSTIterator { | |
private final Deque<TreeNode> s = new ArrayDeque<>(); | |
private TreeNode current; | |
BSTIterator(TreeNode root) { | |
current = root; | |
} | |
public int next() { | |
while (true) { | |
if (current != null) { | |
s.push(current); | |
current = current.left; | |
} else { | |
final TreeNode r = s.pop(); | |
current = r.right; | |
return r.val; | |
} | |
} | |
} | |
public boolean hasNext() { | |
return !s.isEmpty() || current != null; | |
} | |
static class TreeNode { | |
final int val; | |
TreeNode left; | |
TreeNode right; | |
TreeNode(int x) { | |
val = x; | |
} | |
} | |
} |
Analysis
Each hasNext() call takes Θ(1). We access each node of the BST twice, pushing it onto the stack, and later, popping it off the stack. Therefore, our next() call takes only Θ(1) time. We use a stack data structure with height h+1 for storing the nodes during the traversal where h is the height of the tree. Thus, our algorithm uses Θ(h) memory.
References
[1] https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp/0262033844
Comments
Post a Comment