Python programming data structure and algorithm practice _010

Source: Internet
Author: User

Practice content:

Determine if a binary tree T1 is a subtree of another binary tree T2. (T2>T1)

Requirements: Time complexity O (N), Space complexity O (1)

Body Content Summary:

The 1.morris traversal implements the T1,T2 serialization of the first order.

2.KMP algorithm for judging T1 and T2 serialization results (T2>T1)

(1) if Seralize (T1) is a substring of seralize (T2), then T1 is a sub-tree of T2

(2) Otherwise, T1 is not a T2 subtree.

1. Creating a class description tree structure

1 classMyProperty:2     def __init__(self, get_attrib_func):3Self.get_attrib_func =Get_attrib_func4Self.set_attrib_func =None5 6     def __set__(self, instance, value):7         if  notSelf.set_attrib_func:8             RaiseAttributeerror ("can ' t set attribute")9 Self.set_attrib_func (instance, value)Ten  One     def __get__(self, instance, owner): A         returnSelf.get_attrib_func (instance) -  -     defsetter (self, set_attrib_func): theSelf.set_attrib_func =Set_attrib_func -         return Self -  -  + classNode: -     def __init__(self, value): +Self.value =value ASelf.__left=None atSelf.__right=None -  - @MyProperty -     defLeft (self): -         returnSelf.__left -  in @left. Setter -     defLeft (Self, node): toSelf.__left=node +  - @MyProperty the     defRight (self): *         returnSelf.__right $ Panax Notoginseng @right. Setter -     defRight (Self, node): theSelf.__right= Node

2. Using the Morris traversal to realize the sequencing of the two-fork tree

1 defMorris_pre_serialize (head):2     if  notHead:3         return4String = []5Cur =Head6Most_left =None7      whileCur! =None:8Most_left =Cur.left9         ifMost_left! =None:Ten              whileMost_left.right! = None andMost_left.right! =cur: OneMost_left =Most_left.right A  -             ifMost_left.right = = None:#first time to reach the cur node -String.append ("{}{}". Format (Cur.value,"_")) theMost_left.right =cur -Cur =Cur.left -                 Continue -             Else: +Most_left.right = None#second time to reach the cur node -String.append ("#_") +  A         Else: atString.append (str (cur.value) +"_") -String.append ("#_") -Cur =Cur.right -     Else: -String.append ("#_") -  in     return "". Join (String)

3. Implementing the KMP algorithm

1 defKMP (str_x, str_y):2 3     def __get_nexts(str_x):4         ifStr_x isNone:5             returnNone6 7Length =Len (str_x)8         iflength = = 1:9             return[-1]Ten  OneNexts = [0] *length ANexts[0] = 1 -NEXTS[1] =0 -I1, i2 = 2, 1 the          whileI1 <Length: -             ifStr_x[i1-1] = =Str_x[nexts[i2]]: -NEXTS[I1] = Nexts[i2] + 1 -I2, I1 = i1, I1 + 1 +             elifNEXTS[I2]! =-1: -I2 =Nexts[i2] +             Else: ANEXTS[I1] =0 atI2, I1 = i1, I1 + 1 -         returnnexts -  -  -     ifStr_x isNoneorStr_y isNoneorLen (str_y) < 1orLen (str_x) <Len (str_y): -         return-1 in  -len_str_x, len_str_y =Len (str_x), Len (str_y) to  +I1, i2 =0, 0 -  theNexts =__get_nexts(str_y) *  $      whileI1 < len_str_x andI2 <len_str_y:Panax Notoginseng         ifSTR_X[I1] = =Str_y[i2]: -I1, i2 = i1 + 1, I2 + 1 the         elifNEXTS[I2]! =-1: +I2 =Nexts[i2] A         Else: theI1 + = 1 +     returnI1-i2ifI2 = = Len_str_yElse-1

4. Combine Morris traversal, KMP substring judgment, and realize subtree judgment. Time Complex O (N), Spatial complexity O (1)

1 defIs_sub_tree (Head1, head2):2     ifHead1 isNoneorHead2 isNone:3         returnFalse4 5STR1 =morris_pre_serialize (HEAD1)6STR2 =morris_pre_serialize (head2)7 8STR1, str2 = (str2, str1)ifLen (STR1) < Len (str2)Else(str1, str2)9 TenRET =KMP (str1, str2) One  A     returnTrueifRet! =-1ElseFalse

5. Simple test Code

1 if __name__=="__main__":2Tree_1 = Node (1)3Tree_1.left = Node (2)4Tree_1.right = Node (3)5Tree_1.left.left = Node (4)6Tree_1.left.right = Node (5)7Tree_1.right.left = Node (6)8Tree_1.right.right = Node (7)9 Tentree_2 = Node (3) OneTree_2.left = Node (6) ATree_2.right = Node (7) -Tree_2.left.right = Node (8) -     #tree_2 is not tree_1 ' s sub tree the     Print(Is_sub_tree (tree_2, Tree_1))#False -     Print("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~") -Tree_3 = Node (3) -Tree_3.left = Node (6) +Tree_3.right = Node (7) -     #Tree_3 is tree_1 ' s sub tree +     Print(Is_sub_tree (Tree_1, Tree_3))#True

Python programming data structure and algorithm practice _010

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.