题目:
难度:Easy
相关话题:树
、深度优先搜索
、广度优先搜索
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3]
是对称的。
1
/ \
2 2
/ \ / \
3 4 4 3
但是下面这个 [1,2,2,null,3,null,3]
则不是镜像对称的:
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
递归(dfs
):
/**
* 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)return true
function dfs(root1,root2){
if(!root1 && !root2)return true
if(!root1 || !root2)return false
if(root1.val!==root2.val)return false
return dfs(root1.left,root2.right) && dfs(root1.right,root2.left)
}
return dfs(root.left,root.right)
};
迭代(bfs
):
/**
* @来源: Javascript中文网 - 前端进阶资源教程 https://www.javascriptc.com/
* @介绍:一个致力于帮助开发者用代码改变世界为使命的平台,每天都可以在这里找到技术世界的头条内容
* 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)return true
let aux=[root]
while(aux.length>0){
let len=aux.length
if(!check(aux))return false
for(let i=0;i<len;i++){
let node=aux.shift()
if(!node)continue
aux.push(node.left)
aux.push(node.right)
}
}
return true
function check(arr){
let n=arr.length
for(let i=0;i<=Math.floor(n/2);i++){
let j=n-1-i
if(!arr[i] && !arr[j])continue
else if(!arr[i] || !arr[j])return false
else if(arr[i].val!==arr[j].val)return false
}
return true
}
};
扩展阅读: