101. 对称二叉树

83 阅读1分钟

好青年 | leetcode 打卡群 - 打卡记录第 十 天

给你一个二叉树的根节点 root , 检查它是否轴对称。

 

示例 1

image.png

输入:root = [1,2,2,3,4,4,3]
输出:true

示例 2:

输入:root = [1,2,2,null,3,null,3]
输出:false
/**
 * 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) {
    // 对称即左节点等于右节点
    // 模块:1、递归 2、遍历
    if (!root) return true;
    // 这里用递归对比
    const ret = (left, right) => {

        if (!left && !right) { return true };

        if (
            left && right &&
            left.val === right.val &&
            ret(left.left, right.right) &&
            ret(left.right, right.left)
        ) {
            return true
        } else {
            return false
        }
    }
    return ret(root.left, root.right)
};