Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

即为判断两颗二叉树是否相同。输入是用数组表示的二叉树。

 [LeetCode]题100:Same Tree

对于图中的树,它的编号是这样的:A(1)B(2)C(3)D(4)E(5)F(6)G(7)

方法一:DFS

 # DFS 递归循环
        # 判断p或者q是否为空
        if p == q == None:
            return True
        if p==None or q==None:
            return False
        if p.val!=q.val:
            return False
        else:
            return self.isSameTree(p.left,q.left) and self.isSameTree(p.right,q.right)

方法二:堆栈

 # stack 先进后出
        stack = [(p,q)]
        while stack:
            n1,n2=stack.pop()
            if not n1 and not n2:
                continue
            if not n1 or not n2:
                return n1==n2
            if n1.val!=n2.val:
                return False
            stack.append((n1.right,n2.right))
            stack.append((n1.left,n2.left))
        return True

每一次pop先取left的值。其中一开始忽略了n1和n2都为空的情况,此时不能直接返回true,因为只代表此次两个子节点的值为null不代表两个二叉树为空,需要continue跳出循环执行下一次pop,再取两个节点的值进行比较。

示例:

[LeetCode]题100:Same Tree

相关文章:

  • 2021-09-02
  • 2021-05-20
  • 2021-07-30
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-26
猜你喜欢
  • 2021-09-13
  • 2022-01-05
  • 2021-09-10
  • 2021-08-18
  • 2022-03-09
  • 2021-09-04
相关资源
相似解决方案