Solving Symmetric Tree Algorithm problem in JavaScript

var isSymmetric = function(root) {};
const isSymmetric =(root)=> {

};
const isSymmetric =(root)=> {
if (root === null) {
return true;
}
};
const isMirror = (tree1, tree2) => {
// if either node is null, we are at a leaf node. either they are the same, in which case we can return true

// if one is null and the other is not, we can return false
if (tree1 === null || tree2 === null) {
return tree1 === tree2;
}
}
// check the values of the nodes. if they are not the same, we can return false. otherwise, skip this if statement
if (tree1.val !== tree2.val) {
return false;
}
// since we got past the first two if statements, make two recursive calls to test if the children are mirror images
// the left node of the right child should be the same as the right node of the left child
// likewise, the left node of the left child should be the same as the right node of the right child
return isMirror(tree1.left, tree2.right) && isMirror(tree1.right, tree2.left);
};
const isSymmetric = (root) => {
if (root === null) {
return true;
}

// pass in the left and right child nodes
return isMirror(root.left, root.right);
};

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Perezchristian

Perezchristian

Flatiron School Graduate with finance, budget, and tax experience.