Skip to content

Instantly share code, notes, and snippets.

@haase1020
Created December 6, 2021 10:55
Show Gist options
  • Save haase1020/e10cff5fdd2c51a2f7f962459f25ebfd to your computer and use it in GitHub Desktop.
Save haase1020/e10cff5fdd2c51a2f7f962459f25ebfd to your computer and use it in GitHub Desktop.
same tree leetcode #100
// Iterative solution: time complexity: O(n) | space complexity: O(n)
var isSameTree = function (p, q) {
const q1 = [];
q1.push(p);
const q2 = [];
q2.push(q);
while (q1.length && q2.length) {
const curr1 = q1.shift();
const curr2 = q2.shift();
// check for null
if (curr1 === null || curr2 === null) {
if (curr1 !== curr2) {
return false;
} else {
continue;
}
}
//check value
if (curr1.val !== curr2.val) return false;
// add children to queues
q1.push(curr1.left, curr1.right);
q2.push(curr2.left, curr2.right);
}
if (q1.length || q2.length) {
return false;
}
return true;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment