← TCS bank

TCS · Question 1 · Trees

Preorder, Inorder, Postorder Traversals

TreesC++code⏱ O(n)💾 O(h)
Service-based

Problem

Traverse a binary tree in preorder, inorder and postorder.

Approach

Record the node before, between, or after its children.

Time O(n)Space O(h)

How it works

  1. 1Preorder records before children.
  2. 2Inorder records between children.
  3. 3Postorder records after children.

Sample input / output

Input:
root = [1, 2, 3, 4, 5]
Output:
[[1, 2, 4, 5, 3], [4, 2, 5, 1, 3], [4, 5, 2, 3, 1]]

Constraints

0 <= nodes <= 100.

Solution — read it, then walk it

Time O(n)Space O(h)Loops 3Branches 7source · C++
Scroll sideways for wide charts — the view follows the active step.
↻ repeat↻ repeat↻ repeatSTARTinclude <iostream>include <vector>include <climits>using namespace stdCLASS TreeNodeDEFINE valTreeNode *left, *rightTreeNode(int x) : val(x),left(nullptr),right(nullptr) {}TreeNode* buildTree(constvector<int>& vs, intnullMark = INT_MIN)DEFINE levelPrint(TreeNode*root)if (!root) { cout <<"[]" << endl; return;}vector<TreeNode*> q ={root}vector<int> outsize_t qi = 0while (qi < q.size())TreeNode* node = q[qi++]if (!node) continueout.push_back(node->val)q.push_back(node->left)q.push_back(node->right)cout << "["for (size_t i = 0; i <out.size(); ++i)if (i) cout << ", "cout << out[i]cout << "]" << endlDEFINE preorder(TreeNode*root, vector<int>& out)if (!root) returnout.push_back(root->val)preorder(root->left, out)preorder(root->right, out)DEFINE inorder(TreeNode*root, vector<int>& out)if (!root) returninorder(root->left, out)out.push_back(root->val)inorder(root->right, out)DEFINE postorder(TreeNode*root, vector<int>& out)if (!root) returnpostorder(root->left, out)postorder(root->right, out)out.push_back(root->val)DEFINE printVec(constvector<int>& v)cout << "["for (size_t i = 0; i <v.size(); ++i)if (i) cout << ", "cout << v[i]
  • start / end
  • statement
  • condition
  • loop
  • returns
  • definition
1/46

StartSTART

Interactive control-flow diagram and step-by-step code walkthrough.

Recommended resourcesAffiliate links · may earn us a commission

Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Cloud hosting for side projectsShip the portfolio project that gets you hired — free credits for new accounts.Claim credits