![]() |
VOOZH | about |
Given a Binary Tree and an input array. The task is to create an Iterator that utilizes next() and hasNext() functions to perform Inorder traversal on the binary tree.
Examples:
Input: 8 Input Array = [next(), hasNext(), next(), next(), next(), hasNext(), next(), next(), hasNext()]
/ \
3 9
/ \
2 4
\
5Output: [2, true, 3, 4, 5, true, 8, 9, false]
Explanation: According to in order traversal answer to the input array is calculated.
Inorder traversal = {2, 3, 4, 5, 8, 9}Input: 4 Input Array = [hasNext(), next(), next(), hasNext()]
/ \
3 2
\
1Output: [true, 3, 4 true]
Naive Approach: A way is needed to traverse back to the ancestor once we reach the leaf node of the binary tree. A Stack data structure can be used for this.
Algorithm:
- initialize the stack
- set current node = root
- while current != NULL
- add current to stack
- current = current.left
IF the stack is not empty
return true
ELSE
return false
- IF stack is empty (or hasNext() returns false)
- Throw an exception
- ELSE
- Initialize current = stack.top
- Pop the element from the stack
- If current.right != NULL
- Initialize next = current->right
- while next != NULL
- add next to the stack
- next = next.left
- return current
Below is the implementation of above approach
2 true 3 4 5 true 8 9 false
Time Complexity: O(N), Where N is the number of nodes in the binary tree.
Auxiliary Space: O(N), The Stack will hold all N elements in the worst case.
Efficient Approach: Morris Traversal can be used to solve this question using constant space. The idea behind morris traversal is to create a temporary link between a node and the right-most node in its left sub-tree so that the ancestor node can be backtracked. A reference of the ancestor node is set to the right child of the right-most node in its left sub-tree.
Algorithm:
Initialize current = root and rightMost = NULL
IF current != NULL
return true
ELSE
return false
- IF current = NULL ( or hasNext() returns false)
- Throw an exception
- ELSE
- IF current.left = NULL
- Initialize temp = current
- current = current.right
- return temp
- ELSE
- Initialize rightMost = current->left
- while rightMost.right != NULL && rightMost.right != current
- rightMost = rightMost.right
- IF rightMost.right == NULL
- rightMost.right = current
- current = current.left
- ELSE
- temp = current
- rightMost.right = null
- current = current.right
- return current
- Call the function again
Below is the implementation of above approach.
2 true 3 4 5 true 8 9 false
Time Complexity: O(N), where N is the number of nodes in the binary tree. Although we are creating temporary links are created and nodes are traversed multiple times (at most 3 times), the time complexity is still linear.
Auxiliary Space: O(1)