标签:
Given two binary trees, write a function to check if they are equal or not.
Two binary trees are considered equal if they are structurally identical and the nodes have the same value.
class Solution: """ @param a, b, the root of binary trees. @return true if they are identical, or false. """ def isIdentical(self, a, b): if not a and not b: return True if not a or not b : return False if a.val != b.val: return False return self.isIdentical(a.left,b.left) and self.isIdentical(a.right,b.right)
迭代解法并不需要同时维护两个栈,只需要一次push或者pop两个结点就可以了,代码如下:
class Solution: """ @param a, b, the root of binary trees. @return true if they are identical, or false. """ def isIdentical(self, a, b): stack = [b,a] while stack: p1=stack.pop() p2=stack.pop() if not p1 and not p2: continue if not p1 or not p2: return False if p1.val != p2.val: return False stack.extend([p2.right,p1.right]) stack.extend([p2.left,p1.left]) return True
注意在 not a and not b 判断二者都不为空之后,判断两者是否有一个为空的好办法是:not a or not b,有值,则有一个为空。
标签:
原文地址:http://www.cnblogs.com/sherylwang/p/5505688.html