LeetCode Same Tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.