[路飞]_js算法:leetcode 101-对称二叉树

131 阅读1分钟

leetcode 101. 对称二叉树

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

 

示例 1:

输入: 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}
 */
 function compare(p,q){
     if(p==null&&q==null)return true;
     if((p==null&&q!=null)||(p!=null&&q==null))return false;
     let l=compare(p.left,q.right);
     let r=compare(p.right,q.left);
     return p.val==q.val&&l&&r
 }
var isSymmetric = function(root) {
    if(root==null)return true;
    return compare(root.left,root.right)
};