Same Tree

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

Solution: 可以使用盏加循环的方法,分治不仅仅局限于一棵树,分治的思想就是左右分开,虽然是两棵树,算法还是左右分开。

class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p == None and q == None:
            return True
        if p == None or q == None:
            return False
        stackA = [p]
        stackB = [q]

        while stackA and stackB:
            nodeA = self.moveNext(stackA)
            nodeB = self.moveNext(stackB)
            if nodeA.val != nodeB.val:
                return False
        if stackA or stackB:
            return False
        return True

    def moveNext(self, stack):
        node = stack.pop()
        if node.left or node.right:
            if node.left == None:
                node.left = TreeNode('#')
            if node.right == None:
                node.right = TreeNode('#')
            stack.append(node.left)
            stack.append(node.right)
        return node
class Solution(object):
    def isSameTree(self, p, q):
        """
        :type p: TreeNode
        :type q: TreeNode
        :rtype: bool
        """
        if p == None and q == None:
            return True
        if p == None or q == None:
            return False
        return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

Last updated

Was this helpful?