Skip to main content

Build Binary Expression Tree From Infix Expression

描述​

TODO

分析​

这题与Basic Calculator III很类似,唯一的不同是输出结果上,本题是输出一棵树,后者只需要输出一个计算结果。所以本题的代码也很类似,设置两个栈,一个数字栈,一个操作符栈,不过数字栈里存放的是二叉树节点。

代码​

# Basic Calculator III
priority = {
'(': 1,
'+': 2,
'-': 2,
'*': 3,
'/': 3
}

def expTree(self, s: str) -> 'Node':
N = len(s)
nums = []
ops = []
for i in range(N):
c = s[i]
if c.isdigit():
nums.append(Node(c))
elif c == '(':
ops.append(c)
elif c == ')':
while ops[-1] != '(':
self.combine(ops, nums)
ops.pop() # pop '('
elif c in '+-*/':
while ops and priority[ops[-1]] >= priority[c]:
self.combine(ops, nums)
ops.append(c)
else:
# c == ' ', do nothing
pass

while ops:
self.combine(ops, nums)
return nums.pop()

def combine(self, ops, nums):
root = Node(ops.pop())
root.right = nums.pop()
root.left = nums.pop()
nums.append(root)

相关题目​