LC-Construct String from Binary Tree
2018-01-29 17:43
267 查看
# Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def tree2str(self, t): """ :type t: TreeNode :rtype: str """ if not t: return '' left, right = '','' if t.left or t.right: left = '({})'.format(self.tree2str(t.left)) if t.right: right = '({})'.format(self.tree2str(t.right)) return '{}{}{}'.format(t.val,left,right) Sol = Solution() t1 = TreeNode(1) t1.left = TreeNode(4) t1.right = TreeNode(2) print Sol.tree2str(t1)
0,关于树的问题总是很难想出来,经验太少
1,问题就是将一颗二叉树以先序遍历的方式构建为一个带有括号的字符串。Input: Binary tree: [1,2,3,4]
也就是说,如果一个节点有孩子的话,那么左子树不管是否为空都要进行处理。
2,format方法是字符串格式化的输出方式
>>> li = ['hoho',18] >>> 'my name is {} ,age {}'.format('hoho',18) 'my name is hoho ,age 18' >>> 'my name is {1} ,age {0}'.format(10,'hoho') 'my name is hoho ,age 10' >>> 'my name is {1} ,age {0} {1}'.format(10,'hoho') 'my name is hoho ,age 10 hoho' >>> 'my name is {} ,age {}'.format(*li) 'my name is hoho ,age 18'
这种方法用{}来作为输出的标志。
3,算法的思想:
如果树为空,就返回一个空字符串
利用 ‘(’ + (string of child) + ‘)’来记录左孩子和右孩子
如果有右孩子而没有左孩子,仍然需要用空的()来对左孩子进行记录
相关文章推荐
- LeetCode 606 Construct String from Binary Tree
- LeetCode@Tree_606_Construct_String_from_Binary_Tree
- LeetCode Construct String from Binary Tree
- 606. Construct String from Binary Tree
- Construct String from Binary Tree
- 606. Construct String from Binary Tree
- [Leetcode] 536. Construct Binary Tree from String 解题报告
- Leetcode-536. Construct Binary Tree from String
- 【LeetCode 606】 Construct String from Binary Tree (C++)
- [LeetCode] Construct Binary Tree from String 从字符串创建二叉树
- LeetCode606:Construct String from Binary Tree
- LeetCode 536----Construct Binary Tree from String
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- LeetCode Weekly Contest 23 之 536.Construct Binary Tree from String
- Construct String from Binary Tree(leetcode)
- leetcode(606):Construct String from Binary Tree
- 606. Construct String from Binary Tree
- 606. Construct String from Binary Tree
- LeetCode Construct Binary Tree from String