In-order Traversal (Iterative) - Binary Tree
To do an in-order traversal of a binary tree iteratively, we use a stack. Here's a possible implementation:
void inorder(Node *root) {
Node *curr = root;
stack<Node *> st;
while (true) {
if (curr != nullptr) {
st.push(curr);
curr = curr->left;
} else {
if (st.empty()) break;
cout << st.top()->value << '\n';
curr = st.top()->right;
st.pop();
}
}
}
Time complexity
The time complexity is O(n) (where n is the number of nodes in the tree) because of the work we do in the while loop. See the video for more detail.
Space complexity
The space complexity is O(h) (where h is the height of the tree) because of the space taken by the stack. See the video for more detail.