(树)-线索二叉树
class Node:
def __init__(self):
self.data = 0
self.right = None
self.left = None
self.left_thread = 0 # 0没有子节点,1有子节点
self.right_thread = 0
def add(root, val):
newnode = Node()
newnode.data = val
pre = newnode
if root == None:
root = newnode
root.left = root
root.right = None
root.left_thread = 0
root.right_thread = 1
return root
current = root.right
if current == None:
root.right = newnode
newnode.left = root
newnode.right = root
return root
parent = root
pos = 0
while current != None:
if current.data > val:
if pos != -1:
pos = -1
pre = parent
parent = current
if current.left_thread == 1:
current = current.left
else:
current = None
else:
if pos != 1:
pos = 1
pre = parent
parent = current
if current.right_thread == 1:
current = current.right
else:
current = None
if parent.data > val:
parent.left = newnode
parent.left_thread = 1
newnode.left = pre
newnode.right = parent
else:
parent.right = newnode
parent.right_thread = 1
newnode.left = parent
newnode.right = pre
return root
def trace(root):
'''
遍历线索二叉树
:param root:
:return:
'''
t = root
while True:
if t.right_thread == 0:
# 右线索访问中节点
t = t.right
else:
t = t.right
while t.left_thread != 0:
t = t.left
if t != root:
print('[%d]' % t.data, end=' ')
if t == root:
break
data = [1, 7, 3, 4, 5, 2, 9, 11, 13, 15, 12]
root = None
for i in range(len(data)):
root = add(root, data[i])
trace(root)
output:
[2] [3] [4] [5] [7] [9] [11] [12] [13] [15]