DSAintermediate 9 min
Nodes with up to two children, binary search trees, and the ways to walk through a tree.
What a binary tree is, how a binary search tree keeps values in order, and how in-order, pre-order and level-order traversal visit nodes.
File systems, HTML pages (the DOM), databases and decision logic are all trees. Understanding trees is the doorway to graphs, heaps and many interview problems.
A tree is made of nodes connected by edges, starting at one root. In a binary tree, each node has at most two children: left and right.
A binary search tree (BST) adds a rule: everything in a node's left subtree is smaller, everything in its right subtree is larger. That makes searching like binary search: go left or right at each node. For a balanced tree that is O(log n).
To traverse (visit every node) there are a few classic orders:
Visited: []
inorder traversal: left, then node, then right.
8 becomes the root. 3 is smaller so it goes left. 10 is larger so it goes right.1 and 6 go under 3; 14 goes under 10.[ 1, 3, 6, 8, 10, 14 ].Compare with a level-order walk, which goes row by row:
Visited: []
level traversal: level by level, top to bottom.
Add a height(node) function that returns 0 for null and 1 + max(height(left), height(right)) otherwise.
node === null in recursive functions.You finished the DSA lessons available so far. Graphs, recursion and dynamic programming are coming next.
class TreeNode {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
}
function insert(root, value) {
if (root === null) return new TreeNode(value);
if (value < root.value) root.left = insert(root.left, value);
else root.right = insert(root.right, value);
return root;
}
function inOrder(node, out = []) {
if (node === null) return out;
inOrder(node.left, out);
out.push(node.value);
inOrder(node.right, out);
return out;
}
let root = null;
for (const v of [8, 3, 10, 1, 6, 14]) {
root = insert(root, v);
}
console.log(inOrder(root));