Search a binary search tree for one present and one absent value.

Algorithm

Basic Implementation

basic.cs
using System;
using System.Collections.Generic;
using System.Linq;

class Node {
    public int Value;
    public Node? Left;
    public Node? Right;
    public Node(int value, Node? left = null, Node? right = null) { Value = value; Left = left; Right = right; }
}
class Program {
    static string Render(Node? node) {
        if (node == null) return "_";
        if (node.Left == null && node.Right == null) return node.Value.ToString();
        return $"{node.Value}({Render(node.Left)},{Render(node.Right)})";
    }
    static Node SampleTree() => new Node(4, new Node(2, new Node(1), new Node(3)), new Node(6, new Node(5), new Node(7)));
    static string ListString(IEnumerable<int> values) => "[" + string.Join(", ", values) + "]";
    static bool Search(Node? root, int target) { var node = root; while (node != null) { if (target == node.Value) return true; node = target < node.Value ? node.Left : node.Right; } return false; }
    static void Main() { var root = SampleTree(); Console.WriteLine(Search(root, 5) ? "5 found" : "5 not found"); Console.WriteLine(Search(root, 8) ? "8 found" : "8 not found"); }
}

A BST search follows one comparison path. The same pinned tree shows a found path for 5 and a missing path for 8.

Step 1 - Find 5

Search 5 takes right from 4, then left from 6, then matches 5.

Present search path: 4 -> 6 -> 5.4#126#2135match7

Step 2 - Miss 8

Search 8 takes right from 4, right from 6, right from 7, then reaches null.

Absent search path: 4 -> 6 -> 7 -> null.4#126#21357#3nullnot found

Complexity

  • Time: O(h) per search
  • Space: O(1) iterative

Implementation notes

  • Render tree structure explicitly instead of printing node objects.
  • Node is a class, so Left and Right are nullable managed references; the sample tree nodes are allocated by the CLR and reclaimed by GC. The iterative search keeps a Node? node cursor and stops when that reference becomes null.
  • The replay highlights the node, traversal state, queue, path, or search cursor that changes at each step.
search path A comparison chooses one subtree at each step, so whole branches are skipped.