Construct Binary Tree from String
此题要写出简洁的形式实在太难...因为题目确保了此树是一颗complete tree,所以对于结点的处理没有序列化二叉树那道题那么复杂了,思路其实都很直接,注意多位数和负数即可
class Solution(object):
def str2tree(self, s):
"""
:type s: str
:rtype: TreeNode
"""
if not s:
return None
stack = []
n = len(s)
cur = 0
while cur < n:
if s[cur].isdigit():
num = 0
while cur < n and s[cur].isdigit():
num = 10 * num + ord(s[cur]) - ord('0')
cur += 1
stack.append(TreeNode(num))
elif s[cur] == '-':
num = 0
cur += 1
while cur < n and s[cur].isdigit():
num = 10 * num + ord(s[cur]) - ord('0')
cur += 1
stack.append(TreeNode(-num))
elif s[cur] == '(':
stack.append(s[cur])
cur += 1
else:
child = stack.pop()
stack.pop()
if stack[-1].left:
stack[-1].right = child
else:
stack[-1].left = child
cur += 1
return stack[0]