Skip to content

Latest commit

 

History

History
33 lines (28 loc) · 845 Bytes

100.md

File metadata and controls

33 lines (28 loc) · 845 Bytes

100. Same Tree

判断两棵二叉树是否相等。两棵二叉树仅在它们的形状相同且每个节点的值相等时才判为相等。

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:

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)

}