Advertisement
jinhuang1102

536. Construct Binary Tree from String

Jan 16th, 2019
121
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.06 KB | None | 0 0
  1. # 因为是string,所以这道题主要是注意root.val可能是,负值,或是多位数
  2. class Solution:
  3.     def buildTree(self, s):
  4.         if len(s) == 0:
  5.             return None
  6.        
  7.         found = s.find('(')
  8.        
  9.         if found == -1:
  10.             root = TreeNode(s)
  11.             return root
  12.         else:
  13.             root = TreeNode(s[:found])
  14.            
  15.             start = found
  16.             st = []
  17.             for i in range(start, len(s)):
  18.                 if s[i] == '(':
  19.                     st.append('(')
  20.                 elif s[i] == ')':
  21.                     st.pop()
  22.                    
  23.                 if not st and start == found:
  24.                     root.left = self.buildTree(s[start+1:i])
  25.                     start = i + 1
  26.                 elif not st:
  27.                     root.right = self.buildTree(s[start+1:i])
  28.                    
  29.             return root      
  30.  
  31.     def str2tree(self, s):
  32.         """
  33.        :type s: str
  34.        :rtype: TreeNode
  35.        """
  36.         root = self.buildTree(s)
  37.         return root
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement