Master advanced binary tree operations including recursive search, level-first traversal, and depth-first traversal techniques.
class BinaryTree {
search(value) {
return this._searchRecursive(this.root, value);
}
_searchRecursive(node, value) {
// Base cases
if (node === null) return null;
if (node.value === value) return node;
// Recursive cases
const left = this._searchRecursive(node.left, value);
if (left) return left;
return this._searchRecursive(node.right, value);
}
}
levelOrderTraversal() {
if (!this.root) return [];
const result = [];
const queue = [this.root];
while (queue.length > 0) {
const node = queue.shift();
result.push(node.value);
if (node.left) queue.push(node.left);
if (node.right) queue.push(node.right);
}
return result;
}
class BinaryTree {
// In-order traversal
inOrder() {
const result = [];
this._inOrderRecursive(this.root, result);
return result;
}
_inOrderRecursive(node, result) {
if (node) {
this._inOrderRecursive(node.left, result);
result.push(node.value);
this._inOrderRecursive(node.right, result);
}
}
// Pre-order traversal
preOrder() {
const result = [];
this._preOrderRecursive(this.root, result);
return result;
}
_preOrderRecursive(node, result) {
if (node) {
result.push(node.value);
this._preOrderRecursive(node.left, result);
this._preOrderRecursive(node.right, result);
}
}
}
Implement a function to find the maximum depth (height) of a binary tree.
Implement a function that returns an array where each element is the sum of values at that level.
3
/ \
9 20
/ \
15 7
Output: [3, 29, 22] // Level sums
Implement a function that traverses the tree in a zigzag pattern.
3
/ \
9 20
/ \
15 7
Output: [3, 20, 9, 15, 7] // Zigzag pattern
Note: Previously, this course referenced the CodeSignal Arcade for practice, which is no longer available. The LeetCode problems below follow the same principles and are excellent for practicing binary tree traversal techniques.