括号表示法创建二叉树daima
时间: 2023-12-13 18:54:34 浏览: 78
以下是使用括号表示法创建二叉树的代码示例:
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def buildTree(s: str) -> TreeNode:
# 递归结束条件
if not s:
return None
# 找到第一个逗号或结束括号的位置
i = 0
while i < len(s) and (s[i].isdigit() or s[i] == '-'):
i += 1
# 构造当前节点
node = TreeNode(int(s[:i]))
# 递归构造左右子树
if i < len(s):
j, cnt = i + 1, 1 # cnt 用于计数当前节点所在括号层数
while j < len(s) and cnt > 0:
if s[j] == '(':
cnt += 1
elif s[j] == ')':
cnt -= 1
j += 1
node.left = buildTree(s[i+1:j-1])
node.right = buildTree(s[j+1:-1])
return node
```
使用示例:
```python
s = "3(9(4)(5))(20(15)(7))"
root = buildTree(s)
```
这段代码可以创建一个如下的二叉树:
```
3
/ \
9 20
/ \ / \
4 5 15 7
```
阅读全文