Sword refers to the substructure of an offer tree (Python) __python

Source: Internet
Author: User
Topic description

Enter two binary tree a,b to determine whether B is a sub structure. (PS: We agreed that an empty tree is not a substructure of any tree)


Ideas:

Consider using recursive completion, a function nesting recursion to determine whether to match to the starting node, and another to write a recursive to determine whether the right subtree of Saozi is a substructure function.

1, to determine the beginning of a current node, B is a substructure, if not look at the left subtree of a node, if it is not to look at the right subtree of a.

2, if a node starts A and B to coincide with the starting node:

① to determine if B is matched, if the match is finished the description is a substructure

② If a match is over, or the value of a is unequal to B and value, return false directly

③ If the current point is the same, look at the Saozi right subtree at the same time.

The code is as follows:

#-*-Coding:utf-8-*-
"" "
topic Description:
input Two binary tree a,b, Judge B is not a substructure. (PS: We agreed that an empty tree is not a substructure of any tree) ""
Class TreeNode ():
    def __init__ (self,x):
        self.val = x
        self.left = None
        self.right = None        
def hassubtree (proot1,proot2):
    if not pRoot1 or PRoot2: return
        False
    return Is_subtree (Proot1,proot2) or Hassubtree (Proot1.left,proot2) or Hassubtree (proot1.right,proot2)
def is_Subtree ( A,B):
    if not B: return
        True
    if not A/a.val!= b.val: Return
        False return
    is_subtree (a.left,b. left) and Is_subtree (A.right,b.right)


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.