[路飞]_LeetCode_100. 相同的树(广度优先)

114 阅读1分钟

题目

给你两棵二叉树的根节点 p 和 q ,编写一个函数来检验这两棵树是否相同。

如果两个树在结构上相同,并且节点具有相同的值,则认为它们是相同的。

  示例 1:

image.png

输入:p = [1,2,3], q = [1,2,3]
输出:true

来源:力扣(LeetCode)leetcode-cn.com/problems/sa…

解题思路

  1. 如果两棵树都为空则是相同的树
  2. 通过层序遍历的方式遍历两棵树,依次对比对应位置上的节点是否为空,如果不为空则对比值是否相等

代码实现

var isSameTree = function (p, q) {
  const qA = [p]
  const qB = [q]

  while (qA.length || qB.length) {
    const lenA = qA.length
    const lenB = qB.length
    if (lenA !== lenB) return false

    for (let i = 0; i < lenA; i++) {
      const nodeA = qA.shift()
      const nodeB = qB.shift()
      if (!nodeA && !nodeB) continue

      if (
        (!nodeA || !nodeB) ||
        nodeA.val !== nodeB.val ||
        (nodeA.left && !nodeB.left) ||
        (!nodeA.left && nodeB.left) ||
        (nodeB.right && !nodeA.right) ||
        (!nodeB.right && nodeA.right)
      ) {
        return false
      }

      qA.push(nodeA.left)
      qB.push(nodeB.left)
      qA.push(nodeA.right)
      qB.push(nodeB.right)
    }
  }

  return true
};

如有错误欢迎指出,欢迎一起讨论!