Given the root of a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

给定二叉树的根节点,确定该树是不是自己的镜像(换句话说就是关于中线对称)。

限制条件:

  • 树节点的数量范围是 [0, 1000].
  • -100<= Node.val <= 100

解法:

和检查两个二叉树是否相同类似,不过这里是关于根节点对称。

递归:

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isSymmetric = function(root) {
    
    const isSym = function(left, right) {
        if (!left || !right) {
            return left === right;
        }
        
        return left.val === right.val && isSym(left.left, right.right) && isSym(left.right, right.left);
    }
    
    return isSym(root.left, root.right)
};

迭代:

/**
 * Definition for a binary tree node.
 * function TreeNode(val, left, right) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.left = (left===undefined ? null : left)
 *     this.right = (right===undefined ? null : right)
 * }
 */
/**
 * @param {TreeNode} root
 * @return {boolean}
 */
var isSymmetric = function(root) {

    const queue = [root.left, root.right]; // init

    while(queue.length) {
        const left = queue.shift();
        const right = queue.shift();
        
        if (!left && !right) continue;
        if (Boolean(left) !== Boolean(right)) return false;
        if (left.val !== right.val) return false;
        
        queue.push(left.left);
        queue.push(right.right);

        queue.push(left.right);
        queue.push(right.left);
    }
    
    return true;
};