剑指offer:对称二叉树

1、题目描述:

请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

2、解题思路:

如果一棵树是空树,那么他就是对称的;

如果一棵树既不是空树也不是单节点树,而且这棵树和它的子树都是对称的,也就是这棵树的左子树的左子树和右子树的右子树对称,左子树的右子树和右子树的左子树对称。

3、JavaScript实现:

/* function TreeNode(x) {
    this.val = x;
    this.left = null;
    this.right = null;
} */
function check(l,r){
    if(l === null && r === null) return true;
    if(l !== null && r !== null) {
        return (l.val === r.val) && check(l.left, r.right) && check(r.left, l.right);
    };
    return false;
}
function isSymmetrical(pRoot)
{
    // write code here
    if(pRoot === null){
        return true;
    }
    return check(pRoot.left,pRoot.right);
}
原文地址:https://www.cnblogs.com/niconicohang/p/6642231.html