Back to track
#26 Medium Intermediate

Binary Tree Traversals

Open the editor

Problem

Implement preorder, inorder, and postorder traversals.

Constraints

1 <= N <= 200000

Hints

  1. 1

    Use recursion

  2. 2

    Visit order matters

Worked solution

Reference solution

One correct implementation. Alternative approaches that satisfy the constraints are equally valid — the reviewer judges behaviour, not style.

#include <bits/stdc++.h>
using namespace std;

struct Node {
  int val;
  Node* left;
  Node* right;
  Node(int v) : val(v), left(nullptr), right(nullptr) {}
};

void preorder(Node* root, vector<int>& out) {
  if (!root) return;
  out.push_back(root->val);
  preorder(root->left, out);
  preorder(root->right, out);
}
void inorder(Node* root, vector<int>& out) {
  if (!root) return;
  inorder(root->left, out);
  out.push_back(root->val);
  inorder(root->right, out);
}
void postorder(Node* root, vector<int>& out) {
  if (!root) return;
  postorder(root->left, out);
  postorder(root->right, out);
  out.push_back(root->val);
}

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);
  // Build a sample tree manually or from input format
  return 0;
}

© 2026 ChitChat