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)