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.
分析
判断两个二叉树是否相等。常见的二叉树递归回溯算法。
代码
1 2 3 4 5 6 7 8 9 10 11 12
classSolution:
# @param p, a tree node # @param q, a tree node # @return a boolean defisSameTree(self, p, q): ifNone == p andNone == q: returnTrue elif (None == p andNone != q) or (None != p andNone == q): returnFalse else: return p.val == q.val andself.isSameTree(p.left, q.left) andself.isSameTree(p.right, q.right)