题目描述:给定一个二叉树,检查它是否是镜像对称的。
每日学习:
1.复习二叉树的遍历
2.BFS
3.递归和迭代真的难。。。。
题解1:中序遍历+层次识别
var isSymmetric = function(root) {
let result = []
function midOrder(root, k) {
if(root) {
midOrder(root.left, k + 1)
result.push(root.val + '' + k)
midOrder(root.right, k + 1)
}
}
midOrder(root, 1)
// let compare = [...result].reverse()
// let err = 0
// for(let i = 0; i < result.length; i++) {
// if(result[i] != compare[i]) {
// err++
// }
// }
// return err == 0 ? true : false
let i = 0, j = result.length - 1
while (i < j) {
if (result[i] != result[j]) {
return false;
}
i++;
j--;
}
return true
};
题解2:递归
var isSymmetric = function(root) {
if(!root) return true
var isEqual = function(left, right) {
if(!left && !right) return true
if(!left || !right) return false
return left.val === right.val
&& isEqual(left.left, right.right)
&& isEqual(left.right, right.left)
}
return isEqual(root.left, root.right)
};
题解3:迭代
var isSymmetric = function(root) {
if(!root) return true
let stack = [root.left, root.right]
while(stack.length) {
let right = stack.pop()
let left = stack.pop()
if(left && right) {
if(left.val !== right.val) return false
stack.push(left.left)
stack.push(right.right)
stack.push(left.right)
stack.push(right.left)
} else if(left || right) {
return false
}
}
return true
};