yanggengzhen123 / leetcode-group

力扣小组
0 stars 0 forks source link

2022.03.31-第67题-101. 对称二叉树 #69

Open icodeish opened 2 years ago

icodeish commented 2 years ago

https://leetcode-cn.com/problems/symmetric-tree/ 给你一个二叉树的根节点 root , 检查它是否轴对称。

 

示例 1: image

输入:root = [1,2,2,3,4,4,3] 输出:true 示例 2: image

输入:root = [1,2,2,null,3,null,3] 输出:false

yanggengzhen123 commented 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)
};
icodeish commented 2 years ago
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)
}