const binaryTree = {
root: {
key: 1,
left: {
key: 2,
left: { key: 3, left: {}, right: {} },
right: { key: 4, left: {}, right: {} },
},
right: {
key: 2,
left: { key: 4, left: {}, right: {} },
right: { key: 5, left: {}, right: {} },
},
},
};
##Way1
function isMirrorBinaryTree(binaryTree) {
const nodeList = [];
let splitArrayByTier = function (node, index) {
if (node.key) {
splitArrayByTier(node.left, index + 1);
splitArrayByTier(node.right, index + 1);
if (!nodeList[index]) nodeList[index] = [];
nodeList[index].push(node.key);
}
};
splitArrayByTier(binaryTree.root, 0);
for (let i = 1, length = nodeList.length; i < length; i++) {
if (JSON.stringify(nodeList[i]) !== JSON.stringify(nodeList[i].reverse())) {
return false;
}
}
return true;
}
console.log(isMirrorBinaryTree(binaryTree));
##Way2
function isMirrorBinaryTree(root) {
if (root === null) return false;
function isMirror(left, right) {
if (left === null && right === null) return true;
if (left === null || right === null) return false;
if (left.val !== right.val) return false;
return isMirror(left.left, right.right) && isMirror(left.right, right.left);
}
}
console.log(isMirrorBinaryTree(binaryTree.root));
网友评论