Articles > Binary Tree > This article

Pre-order Traversal (Iterative) - Binary Tree

We can do a pre-order traversal of a binary tree iteratively using a stack. Here's a possible implementation:

void preorder(Node *root) {
  if (root == nullptr) return;
  stack<Node *> st;
  st.push(root);
  while (!st.empty()) {
    Node *curr = st.top();
    st.pop();
    cout << curr->value << '\n';
    if (curr->right != nullptr) {
      st.push(curr->right);
    }
    if (curr->left != nullptr) {
      st.push(curr->left);
    }
  }
}

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.

Video with explanation