判断两棵二叉树是否相等。两棵二叉树仅在它们的形状相同且每个节点的值相等时才判为相等。
123456789101112131415
class Solution: def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ # 5 star, 递归, 注意考察的条件 if not p and not q: return True if not p or not q: return False if p.val != q.val: return False return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)
Go:
1234567
func isSameTree(p *TreeNode, q *TreeNode) bool { if p == nil && q == nil {return true} if p == nil || q == nil {return false} if p.Val != q.Val {return false} return isSameTree(p.Left, q.Left) && isSameTree(p.Right, q.Right)}