Skip to content
Learn Netverks

Lesson

Step 25/36 69% through track

tree-traversals

Tree traversals

Last reviewed May 28, 2026 Content v20260528
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches Tree traversals: data structure and algorithm concepts with complexity analysis and interview-ready C++ examples.

Hierarchical and priority data drives search, scheduling, and streaming aggregates.

You will apply Tree traversals in contexts like: File systems, DOM-like hierarchies, schedulers, and top-K dashboards.

Compile and run C++17 snippets in the playground (`int main`, `std::cout`); after each run, state time and space complexity before moving on.

When you can explain the previous lesson's ideas in your own words.

Three DFS orders: preorder (root, left, right), inorder (left, root, right), postorder (left, right, root). Level order uses BFS queue—layer by layer.

When each matters

  • Inorder on BST → sorted values
  • Preorder → copy/serialize tree
  • Postorder → delete tree bottom-up
  • Level order → shortest depth per node in unweighted tree

Recursive inorder

#include 

struct Node { int v; Node* L; Node* R; };

void inorder(Node* n) {
    if (!n) return;
    inorder(n->L);
    std::cout << n->v << " ";
    inorder(n->R);
}

int main() {
    Node a{2, nullptr, nullptr}, b{1, nullptr, nullptr}, c{3, nullptr, nullptr};
    a.L = &b; a.R = &c;
    inorder(&a);
    std::cout << "\n";
    return 0;
}

Complexity

Visit each node once → O(n) time, O(h) recursion stack for height h.

Important interview questions and answers

  1. Q: Inorder output on BST?
    A: Ascending sorted order if BST property holds.
  2. Q: Iterative traversal?
    A: Use explicit stack to simulate recursion—same O(n) time.

Self-check

  1. Write inorder visit order for root 10, left 5, right 15.
  2. What is traversal time for n nodes?

Tip: Inorder on valid BST prints sorted values—memorize that interview fact.

Interview prep

Inorder BST?

Ascending order if BST valid.

Traversal time?

O(n) visit each node once.

Interview tip Lesson completion confidence

Can you explain this lesson in 30 seconds without reading notes?

Not saved yet.

Playground

Runs on the configured server runner (dev: npm run runner with LEARNING_RUNNER_ENABLED=true). Output appears below the editor.

Check yourself

Multiple choice — immediate feedback.

Discussion

Past discussion is visible to everyone. Only logged-in users can post comments and replies.

Starter discussion topics

  • Inorder sorted?
  • BFS level order?

Sign up or log in to post comments and sync lesson progress across devices.

No discussion yet. Be the first to ask a question.

Jump