根据前序和中序列表构造一个二叉树,然后判断二叉树是否是对称的
type TreeNode = {
val: any;
left: TreeNode;
right: TreeNode;
};
function createTreeNode(val: any = null, left: TreeNode = null, right: TreeNode = null) : TreeNode {
const node: TreeNode = {val, left, right};
return node;
}
/**
* 构造二叉树
* @param preArray 前序遍历列表
* @param inArray 中序遍历列表
* @returns 二叉树根节点
*/
function makeTree(preArray: any[], inArray: any[]) : TreeNode {
if (!preArray.length) return null;
const val = preArray[0];
const node = createTreeNode(val);
const index = inArray.indexOf(val);
node.left = makeTree(preArray.slice(1, 1 + i), inArray.slice(0, i));
node.right = makeTree(preArray.slice(i + 1), inArray.slice(i + 1));
return node;
}
/**
* 判断二叉树是否为对称二叉树
* @param tree 二叉树根节点
* @returns 是否为对称二叉树
*/
function isSymmetricTree(tree: TreeNode) : boolean {
if (!tree) return true;
const dfs = function(l: TreeNode, r: TreeNode) : boolean {
if (l === null && r === null) return true;
if (l && r) {
if (l.val !== r.val) return false;
if (dfs(l.left, r.right) && dfs(l.right, r.left)) return true;
}
return false;
};
return dfs(tree.left, tree.right);
}
const preArray = [1, 2, 3, 2, 3];
const inArray = [3, 2, 1, 2, 3];
const tree = makeTree(preArray, inArray);
console.log(isSymmetricTree(tree));