一、题目描述
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
例如,二叉树 [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
示例1
输入:root = [1,2,2,3,4,4,3]
输出:true
示例2
输入:root = [1,2,2,null,3,null,3]
输出:false
限制
0 <= 节点个数 <= 1000
二、题目解析
判断一颗二叉树是否为对称的,即从深度为1的两个对应节点A
,B
开始,递归遍历整棵二叉树,
判断A.left
和B.right
以及A.right
和B.left
的值是否相等。
- 终止条件
- 遍历到的镜像节点均为空,说明匹配完毕,返回
true
- 遍历到的镜像节点的值不相等,包含只有其中一个节点为空的情况,返回false
- 遍历到的镜像节点均为空,说明匹配完毕,返回
- 返回值
A.left
和B.right
是否相等,即recusive(left.left,right.right)A.right
和B.left
是否相等,即recusive(left.right,right.left)
/**
* 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) {
if(root == null) return true;
return recusive(root.left,root.right);
};
var recusive = function(left, right) {
if(left == null && right == null) return true;
if(left == null || right == null || left.val != right.val) return false;
return recusive(left.left,right.right) && recusive(left.right,right.left);
}
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/dui-cheng-de-er-cha-shu-lcof