3. Given the following TypeScript code for LCA, what will be the output if we call
findLCA(root, node5, node1) where
node5 and
node1 are nodes with values 5 and 1 respectively?
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val: number) {
this.val = val;
this.left = null;
this.right = null;
}
}
function findLCA(root: TreeNode | null, p: TreeNode, q: TreeNode): TreeNode | null {
if (!root || root === p || root === q) return root;
const left = findLCA(root.left, p, q);
const right = findLCA(root.right, p, q);
if (left && right) return root;
return left ? left : right;
}
// Tree structure:
// 3
// / \
// 5 1
// / \ / \
// 6 2 0 8
// / \
// 7 4
const root = new TreeNode(3);
const node5 = new TreeNode(5);
const node1 = new TreeNode(1);
root.left = node5;
root.right = node1;
// ... other nodes assigned similarly
const lca = findLCA(root, node5, node1);
console.log(lca?.val);