101. Symmetric Tree

题干简述:

给我们一个二叉树的根节点,判断当前二叉树是否是对称的。

解题思路

101

先看下 leetcode 给出的测试用例一。我们可以看到,以二叉树中轴线为对称轴,左右子树实现了镜像对称。因此,为了得出结果,我们需要比较左右子树是否是对称的,也就是比较如下两个子树:

101-2

比较是否对称很简单,比较相应的左右子节点是否一致,并且取 且 结果就 OK 了。

现在,让我们想一想如果树的层级很深,这里如何使用递归一层层的判断下去呢?实际还是很简单,和判断两个子树是否相同的思路并没有什么区别,不过是交换了一下左右子树比较位置而已。

代码实现如下:

/**
 * 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) {
    if (!root) return true;
    if ((!root.left && root.right) && (root.left && !root.right)) return false;
    let res = checkIfMirror(root.left, root.right);
    return res;
};

var checkIfMirror = function (node1, node2) {
    if (!node1 && !node2) return true;
    if ((!node1 && node2) || (node1 && !node2)) return false;
    return node1.val === node2.val && checkIfMirror(node1.left, node2.right) && checkIfMirror(node1.right, node2.left)
}

Q.E.D.


Take it easy