📅  最后修改于: 2023-12-03 15:25:53.845000             🧑  作者: Mango
在计算机科学中,二叉树是一种常见的数据结构,它由节点组成,每个节点最多有两个子节点。而把二叉树的各级节点值按升序左旋转,就是将每个节点值的数字左循环移位,整体将升序的数字放到树的左侧,可以以此来改变二叉树的形状。
以下是一份Python实现的示例代码,其中包含了创建二叉树,按升序左旋转节点值并打印输出的完整过程:
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def insert(self, value):
if self.root is None:
self.root = Node(value)
else:
self._insert(value, self.root)
def _insert(self, value, curr_node):
if value < curr_node.value:
if curr_node.left is None:
curr_node.left = Node(value)
else:
self._insert(value, curr_node.left)
elif value > curr_node.value:
if curr_node.right is None:
curr_node.right = Node(value)
else:
self._insert(value, curr_node.right)
else:
print("Value already exists in tree.")
def inorder(self, node):
if node is not None:
self.inorder(node.left)
print(node.value, end=' ')
self.inorder(node.right)
def rotate(self, node):
if node is None:
return
node.value = str(int(node.value) + 1)
self.rotate(node.left)
self.rotate(node.right)
tree = BinaryTree()
tree.insert(8)
tree.insert(3)
tree.insert(10)
tree.insert(1)
tree.insert(6)
tree.insert(14)
tree.insert(4)
tree.insert(7)
tree.insert(13)
print("Original tree:")
tree.inorder(tree.root)
print()
print("Left rotated tree:")
tree.rotate(tree.root)
tree.inorder(tree.root)
输出结果为:
Original tree:
1 3 4 6 7 8 10 13 14
Left rotated tree:
2 4 5 7 8 9 11 14 15
可以看到,将二叉树节点值按升序左旋转后,值的升序变化了,同时二叉树结构也发生了变化。