Inorder traversal of a tree

1 min read

https://www.techiedelight.com/inorder-tree-traversal-iterative-recursive/

Left, Root, Right

Recursive

void inorder(Node *root) {
  if (root == nullptr) {
    return;
  }

  inorder(root->left);

  cout << root->data << " ";

  inorder(root->right);
}

Iterative: use stack

void inorderIterative(Node *root) {
  stack<Node *> stack;

  Node *curr = root;

  while (!stack.empty() || curr != nullptr) {
    if (curr != nullptr) {
      stack.push(curr);
      curr = curr->left;
    } else {
      curr = stack.top();
      stack.pop();
      cout << curr->data << " ";

      curr = curr->right;
    }
  }
}
Mirror of a tree
Preorder traversal of a tree