leetcode101.对称二叉树

leetcode101.对称二叉树

题目

给定一个二叉树,检查它是否是镜像对称的。

用例

例如,二叉树 [1,2,2,3,4,4,3] 是对称的。

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

但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的。

    1
   / \
  2   2
   \   \
   3    3

求解

/**
 * 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) {
    //递归比较
    let flag = true
    symmetric(root.left,root.right)
    return flag
    function symmetric(root_1,root_2){
        if((root_1==null&&root_2==null)||flag==false){
            return
        }
        if(root_1==null){
            flag = false
            return
        }
        if(root_2==null){
            flag=false
            return
        }
        if(root_1.val!=root_2.val){
            flag = false
            return
        }
        symmetric(root_1.left,root_2.right)
        symmetric(root_1.right,root_2.left)
    }

};
posted @ 2021-11-22 21:06  BONiii  阅读(29)  评论(0)    收藏  举报