Skip to content

Instantly share code, notes, and snippets.

@mpaccione
Created March 5, 2022 05:43
Show Gist options
  • Save mpaccione/45f8a8f67c5333c2dd0cf7a94028894e to your computer and use it in GitHub Desktop.
Save mpaccione/45f8a8f67c5333c2dd0cf7a94028894e to your computer and use it in GitHub Desktop.
//////////////////
// INSTRUCTIONS //
//////////////////
// Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).
// Input: root = [1,2,2,3,4,4,3]
// Output: true
// Input: root = [1,2,2,null,3,null,3]
// Output: false
const useCase1 = [1, 2, 2, 3, 4, 4, 3];
const output1 = true;
const useCase2 = [1, 2, 2, null, 3, null, 3];
const output2 = false;
const { toUnorderedTree } = require("./helper.js");
const isTreeSymmetric = (tree) => {
if (!tree) {
return Error('Not a valid Binary Tree')
}
const leftBranch = JSON.stringify(tree.left);
(function recursiveSymmetryFlip(node) {
if (node){
const cLeft = node.left ? JSON.parse(JSON.stringify(node.left)) : null
const cRight = node.right ? JSON.parse(JSON.stringify(node.right)) : null
if (node.left) {
node.left.value = cLeft.value ^ cRight.value;
recursiveSymmetryFlip(node.left);
}
if (node.right) {
node.right.value = cRight.value ^ cLeft.value;
recursiveSymmetryFlip(node.right);
}
}
})(tree.right);
const rightBranch = JSON.stringify(tree.right); // we had to flip this and then stringify
console.log(JSON.stringify(leftBranch))
console.log(JSON.stringify(rightBranch))
return leftBranch === rightBranch;
};
module.exports = function () {
describe("Is Tree Symmetric", () => {
it("Use Case 1", () => {
expect(isTreeSymmetric(toUnorderedTree(useCase1))).toEqual(output1);
});
// it("Use Case 2", () => {
// expect(isTreeSymmetric(toUnorderedTree(useCase2))).toEqual(output2);
// });
});
};
// RESULT
// "{\"value\":2,\"left\":{\"value\":3},\"right\":{\"value\":4}}"
// "{\"value\":2,\"left\":{\"value\":7},\"right\":{\"value\":7}}"
// Is Tree Symmetric
// ✗ Use Case 1
// - Expected false to equal true.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment