100.相同的树【简单】
题目链接
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 === null) return;
if (index*2+1 < total) {
leftP = inputList[index*2+1] !== null ? new TreeNode(inputList[index*2+1]): null;
inputList[index*2+1] = leftP;
}
if (index*2+2 < total) {
rightP = inputList[index*2+2] !== null ? 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)
}
var isSameTree = function(p, q) {
if (p === null && q === null) return true;
else if (p === null || q === null) return false;
else if (p.val!== q.val) return false;
else {
const leftRes = isSameTree(p.left, q.left);
const rightRes = isSameTree(p.right, q.right);
return leftRes && rightRes;
}
};
(()=>{
const input = [1,2,1];
const root = initTree(input);
const input2 = [1,1,2];
const root2 = initTree(input2);
console.log('binaryTreePaths', isSameTree(root, root2));
})();