Binary Tree Operations
Understand how to perform essential binary tree operations including searching, insertion, and deletion. Learn traversal methods like depth-first and level-order search, and implement these strategies in Go to manage hierarchical data effectively.
We'll cover the following...
Binary trees store data in a hierarchical structure. Unlike binary search trees (BSTs), they do not follow any ordering rules, so we cannot directly determine where to go when searching or inserting.
Because of this, most operations rely on traversing the tree.
In this lesson, we study three fundamental operations:
Searching
Insertion
Deletion
Searching in a binary tree
Searching in a binary tree means checking whether a given value exists in the tree. Since there is no ordering property, we cannot skip parts of the tree. In the worst case, we may need to visit every node.
A common approach is to use depth-first search (DFS). We start at the root, check its value, and if it does not match, we recursively search the left subtree and then the right subtree.
How this algorithm works
Start at the root node.
If the current node is
nil, returnfalsebecause the value is not found.Check if the current nodeās value matches the target:
If yes, return
true
If not, recursively search the left subtree.
If the value is not found in the left subtree, search the right subtree.
Return
trueif the value is found in either subtree, otherwise returnfalse.
Go implementation
Below is the Go ...
Time complexity: