DEV Community

JB
JB

Posted on • Updated on

Binary Search Trees

Note: I will be referring to Binary Search Trees as BST for the duration of this post.

Resources

  1. Tree & Binary Tree Overviews
  2. BST Overview
  3. More In Depth BST Overview
  4. Search and Insert
  5. Deletes
  6. Breadth First Search
  7. Depth First Search Overview
  8. Depth First Search Implementation

Takeaways:

  • The top level node is called the root node.
  • Nodes to the left are smaller than their parent nodes. Nodes to the right are larger than their parents.
  • A node at the bottom of a tree, meaning it has no child nodes (i.e no reference to a node left or right), is called a leaf node.
  • There are two main ways of traversing a BST: Depth First Search (DFS) and Breadth First Search (BFS).
  • There are three main ways you can perform a DFS: Preorder, Inorder, and Postorder.
  • BFS traverses the tree level by level (so width ways or across the tree). DFS traverses the tree by going down it, and it starts with the left side of the tree.
  • The left side of a root node is called the left subtree and the right is the right subtree. This is not exclusive to a root node, any node can have a subtree off of it.
  • Space for a BST is O(n).
  • Time complexity of operations is good - not the fastest, but not the slowest. All operations on a balanced BST are O(log n) (Logarithmic). For an unbalanced BST all operations are O(n).
  • Due to the time complexity being worse for an unbalanced tree, it is a good idea to periodically rebalance a BST (which I plan to learn more about - maybe starting here).
  • An unbalanced BST is one where there are more levels than necessary, making operations perform less than optimal. For example the height of a BST might be five levels, but the same BST could be represented in three levels instead by reorganizing the nodes. This regorganization is called rebalancing.

Overall the hardest part about implementing a BST is the delete operation. Probably the hardest part was dealing with deleting a node with two child nodes. I learned that in this instance you need to find the inorder successor* and essentially move it to where the deleted node was.

*An inorder successor of a node is the next node in the inorder traversal of the BST. I.E. If you looked at an inorder sequence of nodes, it would be the one after the node being deleted.

As the delete operation was challenging, I added comments explaining it step by step. There are more succinct ways to do it than I chose - but I feel my implementation is easier to follow than most.

Here's the finished implementation of a BST with some test code:

As always, if you found any errors in this post please let me know!

Top comments (0)