Open icodeish opened 2 years ago
function isSymmetric(root: TreeNode | null): boolean {
// 这道题要判断null的情况,然后再对比val值 递归
function compare(left,right){
if(left === null && right !== null || right === null && left !== null){
return false
}else if(left === null && right === null){
return true
}else if(left.val !== right.val){
return false
}
const outSide = compare(left.left,right.right)
const inSide = compare(left.right,right.left)
return outSide && inSide
}
return compare(root.left,root.right)
};
function isSymmetric(root) {
return dfs(root.left, root.right)
}
function dfs(left, right) {
if (left === null && right === null) return true
if (left === null || right === null) return false
if (left.val !== right.val) return false
return dfs(left.left, right.right) && dfs(left.right, right.left)
}
https://leetcode-cn.com/problems/symmetric-tree/ 给你一个二叉树的根节点 root , 检查它是否轴对称。
示例 1:
输入:root = [1,2,2,3,4,4,3] 输出:true 示例 2:
输入:root = [1,2,2,null,3,null,3] 输出:false