Binary Search Tree Flashcards
What is a binary search tree?
Tree data structure in which each node has at most two children. Binary search trees are sorted, where the left child’s value is less than its parent and the right child’s value is greater than the parent.
What are binary search trees good at?
Inserting and searching.
What should the skeleton of a node class look like for BST?
it should have a value, left , and right property.
What should the skeleton of a BST class look like?
It should just have a root property.
What is the time complexity of searching for an element in a Binary Search Tree (BST)?
O(log n), where n is the number of elements in the BST.
Briefly describe the process of searching for an element in a BST.
1 - Start at the root node.
2 - If the element you’re searching for is equal to the current node’s value, you’ve found it.
3 - If the element is less than the current node’s value, traverse to the left child.
4 - If the element is greater than the current node’s value, traverse to the right child.
5 - Repeat steps 2-4 until the element is found or you reach an empty child pointer, indicating the element doesn’t exist.
What is the time complexity of inserting an element into a BST?
O(log n) in the average case, but can be O(n) in the worst case (e.g., inserting elements in sorted order).
Briefly describe the process of inserting an element into a BST.
1 - Start at the root node.
2 - If the tree is empty, create a new node with the element and make it the root.
3 - If the element is less than the current node’s value, traverse to the left child.
4 - If the element is greater than the current node’s value, traverse to the right child.
5 - Repeat steps 2-4 until you reach an empty child pointer.
6 - Create a new node with the element and make it the child of the current node (left if less, right if greater).
What property must hold true for a Binary Search Tree (BST) to be valid?
For any node, all elements in its left subtree must be less than the node’s value, and all elements in its right subtree must be greater than the node’s value.