101. 对称二叉树【简单题】
题目链接
const initTree = (inputList) => {
const total = inputList.length;
if(!inputList[0])return null;
inputList[0] = new TreeNode(inputList[0]);
inputList.forEach((el,index) => {
let leftP = null;
let rightP = null;
if (!el) return;
if (index*2+1 < total) {
leftP = inputList[index*2+1]? new TreeNode(inputList[index*2+1]): null;
inputList[index*2+1] = leftP;
}
if (index*2+2 < total) {
rightP = inputList[index*2+2]? new TreeNode(inputList[index*2+2]): null;
inputList[index*2+2] = rightP;
}
inputList[index].left = leftP;
inputList[index].right = rightP;
});
return inputList[0];
}
function TreeNode(val, left, right) {
this.val = (val===undefined ? 0 : val)
this.left = (left===undefined ? null : left)
this.right = (right===undefined ? null : right)
}
const compare = (left, right) => {
if (!left && !right) return true;
else if (!left || !right) return false;
else if (left && right && left.val !== right.val) return false;
else {
const outsideRes = compare(left.left, right.right);
const insideRes = compare(left.right, right.left);
return outsideRes && insideRes;
}
}
var isSymmetric = function(root) {
return compare(root.left, root.right);
};
(()=>{
const input = [1,2,2,3,4,4,3];
const root = initTree(input);
console.log('root', root);
const res = isSymmetric(root);
console.log('res', res);
})();