已知如下一棵二叉树对应的字符序列(层次遍历序列)为:ABC##EF#G####,其中‘#’表示节点对应的孩子结点为空。现给定一棵二叉树的字符序列,请使用二叉链表构造该二叉树,并输出该二叉树的中序遍历。
时间: 2024-05-11 11:10:06 浏览: 67
```python
# 定义二叉树节点
class TreeNode:
def __init__(self, val):
self.val = val
self.left = None
self.right = None
# 构造二叉树
def buildTree(s):
if not s:
return None
root = TreeNode(s[0])
queue = [root]
i = 1
while queue:
node = queue.pop(0)
if i < len(s) and s[i] != '#':
node.left = TreeNode(s[i])
queue.append(node.left)
i += 1
if i < len(s) and s[i] != '#':
node.right = TreeNode(s[i])
queue.append(node.right)
i += 1
return root
# 中序遍历二叉树
def inorderTraversal(root):
if not root:
return []
res = []
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
res.append(root.val)
root = root.right
return res
# 构造二叉树并输出中序遍历
s = "ABC##EF#G####"
root = buildTree(s)
print(inorderTraversal(root))
```
阅读全文