Skip to content
Learn Netverks

Lesson

Step 26/36 72% through track

bst-basics

BST basics

Last reviewed Jun 1, 2026 Content v20260601
Track mode
server_compiled
Means
Compiled runner
Reading
~1 min
Level
beginner

This lesson

This lesson teaches BST basics: 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 BST basics in contexts like: Interview loops, performance tuning, and foundational CS courses.

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.

In a binary search tree, every node's left subtree has smaller values; right subtree larger. Search/insert follow one path from root—O(h) time where h is height.

Search algorithm

  1. Start at root
  2. If target == value, found
  3. If target < value, go left; else right
  4. Null means missing

Search implementation

#include 

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

Node* search(Node* n, int t) {
    while (n) {
        if (t == n->v) return n;
        n = (t < n->v) ? n->L : n->R;
    }
    return nullptr;
}

int main() {
    Node r{8, nullptr, nullptr}, l{3, nullptr, nullptr}, rr{10, nullptr, nullptr};
    r.L = &l; r.R = &rr;
    std::cout << (search(&r, 3) ? "found\n" : "missing\n");
    return 0;
}

Degenerate BST

Inserting sorted 1,2,3,… into plain BST makes a linked list—height n. Use balanced tree or shuffle inserts in production.

Important interview questions and answers

  1. Q: BST delete overview?
    A: Three cases: leaf, one child, two children (replace with inorder successor)—interview follow-up.
  2. Q: map vs own BST?
    A: std::map is balanced BST—O(log n) guaranteed; hand-rolled BST must rebalance for guarantees.

Self-check

  1. What is BST search complexity in terms of height h?
  2. Why sorted inserts hurt plain BST?

Tip: BST search is O(h)—state height, not always log n without balance.

Interview prep

Search cost?

O(h) height—O(log n) if balanced.

std::map?

Balanced BST tree—O(log n) operations.

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

  • Search cost?
  • Unbalanced risk?

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