101. Symmetric Tree

Description:

Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

     1
   /   \
  2    2
 / \   / \
3  4 4  3

But the following [1,2,2,null,3,null,3] is not:

    1
   / \
  2   2
   \   \
   3    3

My code:

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

var checkEquality = function(left, right) {
    if(left && right) { // 非叶子节点处理
        if(left.val == right.val) {
            return checkEquality(left.left, right.right) && checkEquality(left.right, right.left);
        } else {
            return false;
        }
    } else if(left == right) { // 判断叶子值是否相等
        return true;
    } else {
        return false;
    }
}

Note: 跟100. Same Tree 思路差不多,100是两个树对比,本题可以看作自己与自己的副本对比

你可能感兴趣的:(101. Symmetric Tree)