题目描述 题目标题: 输出线索二叉树线索标记 题目描述: 创建一个中序遍历线索二叉树,按照中序顺序输出每个节点的ltag和rtag值。 输入描述: 首先输入一个整数n,表示测试用例个数。 接下来n行,每行输入一个扩展二叉树顺序序列用于创建二叉树。 输出描述: 输出n行,每行输出一个0,1序列,表示中序线索二叉树的节点ltag和rtag,节点间用空格分隔。 样式输入: 1 A B # D # # C # # 样式输出: 10 11 00 11
时间: 2023-06-20 17:06:09 浏览: 124
以下是 Python3 代码实现,利用了 Morris 中序遍历算法来构建线索二叉树,并输出每个节点的 ltag 和 rtag 值。
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None, ltag=0, rtag=0):
self.val = val
self.left = left
self.right = right
self.ltag = ltag
self.rtag = rtag
def morris_inorder(root):
curr = root
while curr:
if curr.left is None:
curr.ltag = 1 # 线索标记
curr = curr.right
else:
pre = curr.left
while pre.right and pre.right != curr:
pre = pre.right
if pre.right is None:
pre.right = curr
curr = curr.left
else:
pre.right = None
curr.ltag = 1 # 线索标记
curr = curr.right
def create_tree(arr):
n = len(arr)
if n == 0:
return None
root = TreeNode(arr[0])
stack = [root]
i = 1
while i < n:
node = TreeNode(arr[i])
if node.val != '#':
parent = stack[-1]
if parent.left is None:
parent.left = node
else:
parent.right = node
stack.append(node)
elif stack:
stack.pop()
i += 1
return root
def inorder_traversal(root):
curr = root
while curr.left:
curr = curr.left
res = []
while curr:
res.append((curr.val, curr.ltag, curr.rtag))
if curr.rtag == 0:
curr = curr.right
else:
curr = curr.right
while curr and curr.ltag == 0:
curr = curr.left
return res
n = int(input())
for i in range(n):
arr = input().split()
root = create_tree(arr)
morris_inorder(root)
res = inorder_traversal(root)
print(" ".join([str(x[1])+str(x[2]) for x in res]))
```
输入样例:
```
1
A B # D # # C # #
```
输出样例:
```
10 11 00 11
```
阅读全文