Here's how you could test out the previous code using another example input:
xxxxxxxxxx
31
console.log(leastCommonAncestor(root, 1, 8).val);
class Node {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
​
function leastCommonAncestor(root, node1, node2) {
if (root.val > node1 && root.val > node2) {
return leastCommonAncestor(root.left, node1, node2);
} else if (root.val < node1 && root.val < node2) {
return leastCommonAncestor(root.right, node1, node2);
} else {
return root;
}
}
​
// 7
// / \
// 4 8
// / \
// 1 5
​
const root = new Node(7);
root.left = new Node(4);
root.left.left = new Node(1);
root.left.right = new Node(5);
root.right = new Node(8);
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment