Return true if two binary trees have the same structure and the same node values.
Walk both trees in lockstep with a queue of node pairs, comparing each pair.
1function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {2const queue: [TreeNode | null, TreeNode | null][] = [[p, q]];3while (queue.length) {4const [a, b] = queue.shift()!;5if (!a && !b) continue;6if (!a || !b || a.val !== b.val) return false;7queue.push([a.left, b.left], [a.right, b.right]);8}9return true;10}
Queue the root pair.
Space: play/pause · ←/→: step