I'm currently tackling the challenge named 'Merge Two Binary Tree' on leetcode with TypeScript. My solution is passing the tests successfully, but the compiler is throwing an error that says:
https://i.sstatic.net/KZYmJ.png
What's puzzling me is that I believe I've covered all cases and in theory, 'root2' should never be null at that particular point where the compiler is complaining about it being possibly null.
Could it be that I overlooked a scenario or am I misunderstanding how the compiler operates..?
Your guidance in the right direction would be greatly appreciated.
This is my solution:
const mergeTrees = (
root1: TreeNode | null,
root2: TreeNode | null
): TreeNode | null => {
if (!root1 && !root2) return null;
if (root1 && root2)
return new TreeNode(
root1.val + root2.val,
mergeTrees(root1.left, root2.left),
mergeTrees(root1.right, root2.right)
);
if (root1 && !root2)
return new TreeNode(
root1.val,
mergeTrees(root1.left, null),
mergeTrees(root1.right, null)
);
return new TreeNode(
root2.val,
mergeTrees(null, root2.left),
mergeTrees(null, root2.right)
);
}