Builds onTree traversalBinary search
01The idea
A binary search tree, or BST, is a binary tree with an ordering rule. For every node, all values in its left subtree are smaller, and all values in its right subtree are bigger.
That rule gives you three things.
- Searching works like binary search. Compare the target with the node. If it is smaller, go left. If it is bigger, go right. Each step drops a whole subtree. The search takes O(h), where h is the height of the tree.
- Inserting follows the same path. Walk down as if searching, and put the new value where the walk falls off the tree.
- An inorder traversal, which visits left subtree, node, right subtree, lists the values in sorted order.
The height sets the speed. A balanced BST with n nodes has a height of about log₂ n, so operations take O(log n). If you insert values that are already sorted, every node gets only a right child. The tree becomes a line, and operations take O(n). Libraries avoid that with self-balancing trees. Java's TreeMap is one. Python has no built-in balanced tree, so problems that need one use a sorted list with bisect instead.
The rule covers whole subtrees. A node's value must be bigger than everything in its left subtree, including its grandchildren.
02How to spot it
The problem is about BST properties when:
- the input is called a binary search tree, or the tree is built by inserting values
- the question involves order: the kth smallest value, the closest value to a target, the next bigger value
- the question involves ranges: count, sum or list the values between lo and hi
- you must check whether a tree follows the BST rule
The signals for the technique are "skip" and "sorted". If you can rule out a whole subtree with one comparison, do it. If you need the values in order, use an inorder traversal.
Sign in to read the rest of this lesson
The worked example, the interactive visualization, the code template and a short quiz that marks the lesson as done in your study plans.
Sign in to continue