Categories
Binary Search Recursion

Binary Search

function binarySearch(arr, n, start = 0, end = arr.length) {
let mid = Math.floor((end + start) / 2);
if (arr[mid] === n) return mid;

if (start < end - 1) {
if (n > arr[mid]) {
return binarySearch(arr, n, mid, end);
} else {
return binarySearch(arr, n, start, mid);
}
}
return -1;
}
Categories
Binary Tree Leetcode Recursion

Is Same Tree

let isSameTree = function(p, q) {

if (p === q) return true;
if (p?.val !== q?.val) return false;

return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
};
Categories
Binary Tree Leetcode Recursion

Invert a Binary Tree

let invertTree = function(root) {

    if (root) {
        const right = root.right;
        root.right = invertTree(root.left)
        root.left = invertTree(right)
        return root;
    }
    return null;
};