表达式为a*b-c的二叉树的代码
时间: 2024-05-01 20:16:35 浏览: 180
二叉树的C语言代码
```python
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
def buildTree(s: str) -> TreeNode:
if not s:
return None
stack = []
i = 0
while i < len(s):
if s[i].isdigit() or s[i] == '-':
start = i
while i < len(s) - 1 and (s[i + 1].isdigit() or s[i + 1] == '-'):
i += 1
num = int(s[start:i + 1])
node = TreeNode(num)
if stack:
if not stack[-1].left:
stack[-1].left = node
else:
stack[-1].right = node
stack.append(node)
elif s[i] == '*' or s[i] == '/':
stack[-1].val = s[i]
elif s[i] == '+':
if stack[-1].val == '*' or stack[-1].val == '/':
node = stack.pop()
if not stack[-1].left:
stack[-1].left = node
else:
stack[-1].right = node
stack[-1].val = s[i]
elif s[i] == '-':
if i == 0 or s[i - 1] in ['+', '-', '*', '/']:
start = i
while i < len(s) - 1 and (s[i + 1].isdigit() or s[i + 1] == '-'):
i += 1
num = int(s[start:i + 1])
node = TreeNode(num)
if stack:
if not stack[-1].left:
stack[-1].left = node
else:
stack[-1].right = node
stack.append(node)
else:
if stack[-1].val == '*' or stack[-1].val == '/':
node = stack.pop()
if not stack[-1].left:
stack[-1].left = node
else:
stack[-1].right = node
stack[-1].val = s[i]
i += 1
return stack[0]
```
使用示例:
```python
s = "a*b-c"
root = buildTree(s)
```
该代码实现了将字符串表达式转换为二叉树的过程,其中每个节点的值都是一个运算符或者数字。可以通过遍历该二叉树的方式求得表达式的值。
阅读全文