1 class Solution(object):
 2     def __init__(self):
 3         self.List = list()
 4 
 5     def rdfs(self,S):
 6         if S != '':
 7             length = len(S)
 8             depth = len(self.List)
 9             tempval = ''
10             tempdepth = 0
11             for i in range(length):
12                 s = S[i]
13                 if s != '-':
14                     tempval += s
15                     if i == length - 1:
16                         while depth != tempdepth:
17                             self.List.pop(-1)
18                             depth = len(self.List)
19                         parent = self.List[-1]
20                             
21                         val = int(tempval)
22                         t = TreeNode(val)
23                         if parent.left == None:
24                             parent.left = t
25                         elif parent.right == None:
26                             parent.right = t
27                             
28                 else:
29                     if tempval != '':
30                         while depth != tempdepth:
31                             self.List.pop(-1)
32                             depth = len(self.List)
33                         parent = self.List[-1]
34                             
35                         val = int(tempval)
36                         t = TreeNode(val)
37                         if parent.left == None:
38                             parent.left = t
39                             self.List.append(t)
40                             self.rdfs(S[i:])
41                         elif parent.right == None:
42                             parent.right = t
43                             self.List.append(t)
44                             self.rdfs(S[i:])
45                         break
46                     else:
47                         tempdepth += 1
48         else:
49             return None
50 
51     def recoverFromPreorder(self, S: str) -> 'TreeNode':
52         tempval = ''
53         length = len(S)
54         for i in range(length):
55             s = S[i]
56             if s != '-':#数字
57                 tempval += s
58                 if i == length - 1:
59                     val = int(tempval)
60                     root = TreeNode(val)
61 
62             else:#遇到横线,数字结束
63                 val = int(tempval)
64                 root = TreeNode(val)
65                 self.List.append(root)
66                 self.rdfs(S[i:])
67                 self.List.pop(-1)
68                 return root
69         return root

 

posted on 2019-04-14 18:20  Sempron2800+  阅读(232)  评论(0编辑  收藏  举报