您的位置:首页 > 其它

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) + ‘)’来记录左孩子和右孩子

如果有右孩子而没有左孩子,仍然需要用空的()来对左孩子进行记录
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: