Binary Search Trees (BST) are special cases of binary trees. Binary trees are trees where each element or node has no more than 2 children.
The tree below is a binary tree
1
/ \
2 3
/ \
4 5
Binary trees are composed of nodes, where each node in the tree has at most 2 children. Nodes typically hold the following properties:
class TreeNode {
int data;
TreeNode left;
TreeNode right;
}
1
2
3
4
5
are the data value of tree nodes in the example above.
For example, the root
is the base of the tree and the first node at the top. In our example, the node holding the data value 1
is the root. We can call the value of a Node following typical class syntax.
This tree, however, is not a binary tree because 1
has 4 children 2 3 4 5
1
/ / \ \
2 3 4 5
BSTs are special in that for each node, all nodes to the left are less than or equal to it, and all nodes to the right are greater than it. Due to this property, lookups in a BST take O(logN) time on average if the tree is well-balanced.
If we were to put our winning lottery numbers into BST form, it could look something like this:
1, 2, 5, 10, 16, 20, 23, 36, 40, 41, 45
20
/ \
5 40
/ \ / \
2 16 36 41
/ / / \
1 10 23 45
BSTs are the best options when trying to optimize for efficient searching and flexible updates. Unsorted linked lists have O(1)
insertion and deletion operations, but require O(N)
for search operations. If an array is sorted, searching can beO(logN)
, but updating the array by adding or deleting elements is can be O(N)
in the worst cases.
On the other hand, BSTs have more overhead and complexity to initialize and maintain. Arrays and linked lists are more straight forward due to their one dimensional structure. Trees require more thought due to its multi-dimension structure.
Check out CodePath guide on Binary Trees
What are some common questions we should ask our interviewer?
Are there any special techniques that we can use to help make this easier?
Prerequisites that you should be familiar with before: Recursion, stack, queue
See if the current node is a leaf and whether the accumulated sum, i.e. path sum, is equal to our target.
Recursively calculating the path sum of left subtrees and right subtrees.
Tips:
Average Case | Worst Case | |
---|---|---|
Access | O(logn) | O(n) |
Search | O(logn) | O(n) |
Insertion | O(logn) | O(n) |
Deletion | O(logn) | O(n) |