Binary Tree Operations
Explore the core operations of binary trees including searching, insertion, and deletion through practical JavaScript implementations. Understand how depth-first search and level-order traversal enable efficient management in unordered binary trees. Master techniques to maintain tree structure and handle nodes effectively.
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. As 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
None, 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.
JavaScript implementation
Below is the JavaScript implementation of search in a binary tree.
search(root, target) {// Base case: if the current node is null, the value is not foundif (root === null) {return false;}// Check if the current node's value matches the targetif (root.data === target) {return true;}// Recursively search in the left subtree OR right subtree// If found in either, return truereturn this.search(root.left, target) || this.search(root.right, target);}
Time complexity: