标签:tco ack tin nal whether problem proc .com ted
Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node‘s descendants. The tree s could also be considered as a subtree of itself.
Example 1:
Given tree s:
3 / 4 5 / 1 2
Given tree t:
4 / 1 2
Return true, because t has the same structure and node values with a subtree of s.
Example 2:
Given tree s:
3 / 4 5 / 1 2 / 0
Given tree t:
4 / 1 2
Return false.
Solution:
1 def helperRecursiveInOrder(root, l): 2 if root is None: 3 l.append (str("#")) 4 else: 5 helperRecursiveInOrder(root.left, l) 6 l.append(str(root.val)) 7 helperRecursiveInOrder(root.right, l) 8 9 10 def helperRecursivePreOrder(root, l): 11 if root is None: 12 l.append (str("#")) 13 else: 14 l.append(str(root.val)) 15 helperRecursivePreOrder(root.left, l) 16 helperRecursivePreOrder(root.right, l) 17 18 19 lsIn = [] 20 helperRecursiveInOrder(s, lsIn) 21 ltIn = [] 22 helperRecursiveInOrder(t, ltIn) 23 strSIn = ",".join(lsIn) 24 strTIn = ",".join(ltIn) 25 26 lsPre = [] 27 helperRecursivePreOrder(s, lsPre) 28 ltPre = [] 29 helperRecursivePreOrder(t, ltPre) 30 strSPre = ",".join(lsPre) 31 strTPre = ",".join(ltPre) 32 #print ("str: ", strSPre, strTPre, lsPre) 33 if(strTIn in strSIn and strTPre in strSPre): 34 return True 35 else: 36 return False
1 def helperRecursivePreOrder(root, l): 2 if root is None: 3 l.append (str("#")) 4 else: 5 l.append(‘,‘ + str(root.val)) 6 helperRecursivePreOrder(root.left, l) 7 helperRecursivePreOrder(root.right, l) 8 lsPre = [] 9 helperRecursivePreOrder(s, lsPre) 10 ltPre = [] 11 helperRecursivePreOrder(t, ltPre) 12 strSPre = ",".join(lsPre) 13 strTPre = ",".join(ltPre) 14 #print ("str: ", strSPre, strTPre, lsPre) 15 if(strTPre in strSPre): 16 return True 17 else: 18 return False 19
[Leetcode] Binary tree-- 572. Subtree of Another Tree
标签:tco ack tin nal whether problem proc .com ted
原文地址:http://www.cnblogs.com/anxin6699/p/7261195.html