|
| 1 | +/* |
| 2 | + Write a function that takes in a Binary Tree and returns if that tree is symmetrical. A tree is symmetrical |
| 3 | + if the left and right subtrees are mirror images of each other. |
| 4 | +*/ |
| 5 | +class BinaryTree { |
| 6 | + constructor(value, left = null, right = null) { |
| 7 | + this.value = value; |
| 8 | + this.left = left; |
| 9 | + this.right = right; |
| 10 | + } |
| 11 | +} |
| 12 | + |
| 13 | +function isSymmetricalTreeIterative(tree) { |
| 14 | + const stackLeft = (tree && [tree.left]) || []; // Initialize stackLeft with the left child of the root node |
| 15 | + const stackRight = (tree && [tree.right]) || []; // Initialize stackRight with the right child of the root node |
| 16 | + |
| 17 | + // Perform mirror traversal of the left and right subtrees |
| 18 | + while (stackLeft.length > 0) { |
| 19 | + const left = stackLeft.pop() || null; // Pop the top node from stackLeft |
| 20 | + const right = stackRight.pop() || null; // Pop the top node from stackRight |
| 21 | + |
| 22 | + if (!left && !right) { |
| 23 | + continue; // Both left and right subtrees are symmetric, continue to the next iteration |
| 24 | + } |
| 25 | + |
| 26 | + if (!left || !right || left.value !== right.value) { |
| 27 | + return false; // Asymmetry detected, tree is not symmetric |
| 28 | + } |
| 29 | + |
| 30 | + // Push the children of left and right onto the respective stacks in reverse order |
| 31 | + if (left) { |
| 32 | + stackLeft.push(left.left, left.right); |
| 33 | + } |
| 34 | + if (right) { |
| 35 | + stackRight.push(right.right, right.left); |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + return true; // Tree is symmetric |
| 40 | +} |
| 41 | + |
| 42 | +// Example usage: |
| 43 | +// Construct a symmetric tree |
| 44 | +const symmetricTree = new BinaryTree( |
| 45 | + 1, |
| 46 | + new BinaryTree(2, new BinaryTree(3), new BinaryTree(4)), |
| 47 | + new BinaryTree(2, new BinaryTree(4), new BinaryTree(3)) |
| 48 | +); |
| 49 | + |
| 50 | +console.log(isSymmetricalTreeIterative(symmetricTree)); // Output: true |
0 commit comments