Iam_Sandeep

Binary tree from string

Mar 12th, 2022
1,587
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.99 KB | None | 0 0
  1. link="https://www.lintcode.com/problem/880/"
  2. """
  3. Definition of TreeNode:
  4. class TreeNode:
  5.    def __init__(self, val):
  6.        self.val = val
  7.        self.left, self.right = None, None
  8. """
  9.  
  10. class Solution:
  11.     def str2tree(self, s):
  12.         n,st,i=len(s),[],0
  13.         while i<n:
  14.             if s[i]=='-':
  15.                 i+=1
  16.                 num=0
  17.                 while i<n and s[i].isdigit():
  18.                     num=num*10+int(s[i])
  19.                     i+=1
  20.                 i-=1
  21.                 st.append(TreeNode(-num))
  22.             elif s[i].isdigit():
  23.                 num=0
  24.                 while i<n and s[i].isdigit():
  25.                     num=num*10+int(s[i])
  26.                     i+=1
  27.                 i-=1
  28.                 st.append(TreeNode(num))
  29.             elif s[i]==')':
  30.                 t=st.pop()
  31.                 if st[-1].left:
  32.                     st[-1].right=t
  33.                 else:
  34.                     st[-1].left=t
  35.             i+=1
  36.         return st[0]
  37.            
  38.  
Advertisement
Add Comment
Please, Sign In to add comment