LeetCode Same Tree
Same Tree for solving LeetCode Problems
Original question
Determine whether two binary trees are equal. The two binary trees are judged to be equal only when they have the same shape and each node has the same value.
Note:
None
Example:
Input:
2 2p = / \ q = / \ 1 3 1 3
Output: True
Solutions
Tree-related problems are generally better understood using recursive methods. If the nodes corresponding to the two trees are empty, they are equal. If the values are equal, the left and right Subtrees of the two trees are determined to be equal. Otherwise, the two trees are considered unequal.
AC Source Code
# 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 """ if not q and not p: return True elif not p or not q: return False elif p.val != q.val: return False else: return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)if __name__ == "__main__": None