[LeetCode]题100:Same Tree
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.
即为判断两颗二叉树是否相同。输入是用数组表示的二叉树。
对于图中的树,它的编号是这样的: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,再取两个节点的值进行比较。
示例: