http://www.lintcode.com/zh-cn/problem/subtree/
"""
Definition of TreeNode:
class TreeNode:
def __init__(self, val):
self.val = val
self.left, self.right = None, None
"""
class Solution:
preoder_list = []
inoder_list = []
# @param T1, T2: The roots of binary tree.
# @return: True if T2 is a subtree of T1, or false.
def pre_Traverse_to_list(self, node):
if(node != None):
# print Solution.preoder_list
Solution.preoder_list.append(str(node.val))
self.pre_Traverse_to_list(node.left)
self.pre_Traverse_to_list(node.right)
return Solution.preoder_list
def in_Traverse_to_list(self, node):
if(node != None):
self.in_Traverse_to_list(node.left)
Solution.inoder_list.append(str(node.val))
self.in_Traverse_to_list(node.right)
return Solution.inoder_list
def isSubtree(self, T1, T2):
T1 = (''.join(self.pre_Traverse_to_list(T1)),''.join(self.in_Traverse_to_list(T1)))
Solution.preoder_list = []
Solution.inoder_list = []
T2 = (''.join(self.pre_Traverse_to_list(T2)),''.join(self.in_Traverse_to_list(T2)))
if set(T1[0]) == 9 and set(T2[0]) == 9:
return False
if (T2[0] in T1[0]) and ( T2[1] in T1[1]) :
return True
else:
return False
http://www.lintcode.com/zh-cn/problem/fast-power/
def fastPower2(self,a,n,b):
if n == 1:
return a%b
else:
if (n%2==0):
return self.fastPower2(a,(n/2),b)**2%b
else:
return self.fastPower2(a,(n-1)/2,b)**2*a%b
1
just4test 2016-07-17 09:18:38 +08:00 1
几个问题:
1. “ if set(T1[0]) == 9 and set(T2[0]) == 9:”这句话中, 9 这个 magic num 是哪儿来的? 2. 建议你合成字符串时加入空格。否则: 1 / 和 11 这两个你会认为是相同的树,他们的前序和中序合成字符串都是 11. 1 3.将树转换为字符串 /数组再判断终究是异端。还是老老实实对比吧,这题不难别老想歪。 |
4
param 2016-07-19 00:46:11 +08:00
我仿佛又听到有人在背后 @我
|
6
saxon OP @param
http://www.lintcode.com/zh-cn/problem/fast-power/ # def fastPower2(self,a,n,b): # if n == 1: # return a%b # else: # # if (n%2==0): # return self.fastPower2(a,(n/2),b)**2%b # else: # return self.fastPower2(a,(n-1)/2,b)**2*a%b |