题目判断二叉树是对称
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree [1,2,2,3,4,4,3] is symmetric:
判断一个给出的二叉树是否关于中心对称
- Example 1
1
/ \
2 2
/ \ / \
3 4 4 3
output: true
- Example 2
1
/ \
2 2
\ \
3 3
Output: true
- 解法
var isSymmetric = function(root) {
if(root === null) return true
return isSymmetricHelp(root.left,root.right)
};
function isSymmetricHelp(left,right){
// 两个节点都为null
if(!left && !right) return true
//一个节点为null,一个不是null
if((left === null && right !== null) || (left !== null && right === null))return false
//节点都存在子节点,但是这两个节点的值不一样
if(left.val !== right.val) return false
// 递归调用,注意这里有我是关于中心对称,而且每个节点有两个子节点,所以调用两次
return isSymmetricHelp(left.left,right.right) && isSymmetricHelp(left.right,right.left)
}
网友评论