Advertisement
jinhuang1102

606. Construct String from Binary Tree

Jan 15th, 2019
127
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.64 KB | None | 0 0
  1. """
  2. 这道题只需要注意一点就是,当左子树为null而右子树不为null的时候要把左子树'()'打印出来
  3. """
  4. class Solution:
  5.     def preorder(self, root):
  6.         if not root:
  7.             return ''
  8.        
  9.         if not root.left and root.right:
  10.             return "(" + str(root.val) + "()" + self.preorder(root.right) + ")"
  11.         else:
  12.             return "(" + str(root.val) + self.preorder(root.left) + self.preorder(root.right) + ")"
  13.    
  14.     def tree2str(self, t):
  15.         """
  16.        :type t: TreeNode
  17.        :rtype: str
  18.        """
  19.         _str = self.preorder(t)
  20.        
  21.         return _str[1:-1]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement