101. 对称二叉树

117 阅读1分钟
  1. 对称二叉树 leetcode 链接leetcode.cn/problems/sy…

1. 题目描述

给你一个二叉树的根节点 root , 检查它是否轴对称。

image.png

image.png

2. 思路

利用层序遍历,每次出队出两个,入队 对称入4个。 相当于是 层序对称遍历

image.png

function isSymmetricalbinaryroot(root){
   
    // 如果两个都是null 也否和逻辑
    // 加了可选符号 也否和逻辑
     const queue = []
     if(typeof root?.left === "object"){
        queue.push(root.left)
     }
     if(typeof root?.right === "object"){
        queue.push(root.right)
     }
  
     while(queue.length){
         const node1 = queue.shift()
  
         const node2 = queue.shift()
    
         // 队列中只可能有两种值 [{},null]
         if(node1?.val !== node2?.val){
             return false
         }

         // 对象和null 都是object
         if(typeof node1?.left === "object"){
            queue.push(node1?.left)
         }
         if(typeof node2?.right === "object"){
            queue.push(node2.right)
         }
         if(typeof node1?.right === "object"){
            queue.push(node1.right)
         }
         if(typeof node2?.left === "object"){
            queue.push(node2?.left)
         }
     }
     return true

}

console.log(isSymmetricalbinaryroot(root))

3. 总结

  • 正常层序遍历出队一个,依次入队两个,而这个对入队的个数和顺序,出对的个数 做了调整。