leetcode: 100. Same Tree

来源:互联网 发布:键盘记录软件手机 编辑:程序博客网 时间:2024/06/01 14:50

Q

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Example 1:

Input:     1         1      / \       / \     2   3     2   3    [1,2,3],   [1,2,3]Output: true

Example 2:

Input:     1         1      /           \     2             2    [1,2],     [1,null,2]Output: false

Example 3:

Input:     1         1      / \       / \     2   1     1   2    [1,2,1],   [1,1,2]Output: false

AC

# Definition for a binary tree node.class TreeNode(object):    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution(object):    def isSameTree(self, p, q):        """        :type p: TreeNode        :type q: TreeNode        :rtype: bool        """        stack = [(p, q)]        while stack:            node1, node2 = stack.pop()            if not node1 and not node2:                continue            if None in (node1, node2) or node1.val != node2.val:                return False            if node1.val == node2.val:                stack.append((node1.left, node2.left))                stack.append((node1.right, node2.right))        return True# Time:  O(n)# Space: O(h), h is height of binary tree# Definition for a  binary tree nodeclass TreeNode:    def __init__(self, x):        self.val = x        self.left = None        self.right = Noneclass Solution2(object):    def isSameTree(self, p, q):        if p is None and q is None:            return True        if p is not None and q is not None:            return p.val == q.val and self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)        return Falseif __name__ == "__main__":    root1, root1.left, root1.right = TreeNode(1), TreeNode(2), TreeNode(3)    root2, root2.left, root2.right = TreeNode(1), TreeNode(2), TreeNode(3)    assert Solution().isSameTree(root1, root2) == True