Skip to content

Instantly share code, notes, and snippets.

@haase1020
Last active December 4, 2021 10:57
Show Gist options
  • Save haase1020/cff4d99e68ea66174de37454db5342e5 to your computer and use it in GitHub Desktop.
Save haase1020/cff4d99e68ea66174de37454db5342e5 to your computer and use it in GitHub Desktop.
#101 LeetCode Symmetric Tree Iterative Javascript Solution
var isSymmetric = function (root) {
if (!root) {
return "no tree was provided 🤔"; // return true
}
if (!root.left && !root.right) {
return "you have a symmetric tree that only has 1 node...the root 🌱!"; // return true
}
let queue = [];
queue.unshift(root);
queue.unshift(root);
let leftNode;
let rightNode;
while (queue.length) {
console.log({ queue }); // check queue size to calculate space complexity. In symmetric tree can be num nodes +1
console.log("running this code block"); // this will run at most for the total number of nodes in the tree
leftNode = queue[0];
queue.shift();
rightNode = queue[0];
queue.shift();
if (leftNode.value !== rightNode.value) {
return "your tree is not symmetric 🌴"; // return false
}
if (leftNode.left && rightNode.right) {
queue.unshift(leftNode.left);
queue.unshift(rightNode.right);
} else if (leftNode.left || rightNode.right) {
return "your tree is not symmetric 🌴"; // return false
}
if (leftNode.right && rightNode.left) {
queue.unshift(leftNode.right);
queue.unshift(rightNode.left);
} else if (leftNode.right || rightNode.left) {
return "your tree is not symmetric 🌴"; // return false
}
}
return "you have a perfectly symmetric tree! 🌲"; //return true
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment