Python程序打印左子树中的节点
当需要打印左子树中的节点时,可以创建一个包含方法的类,这些方法可以定义为设置根节点、执行中序遍历、将元素插入到根节点的右侧、插入到根节点的左侧等等。创建类的实例,然后可以使用这些方法执行所需的操作。
以下是相同内容的演示 -
示例
class BinaryTree_struct:
def __init__(self, data=None):
self.key = data
self.left = None
self.right = None
def set_root(self, data):
self.key = data
def inorder_traversal(self):
if self.left is not None:
self.left.inorder_traversal()
print(self.key, end=' ')
if self.right is not None:
self.right.inorder_traversal()
def insert_at_left(self, new_node):
self.left = new_node
def insert_at_right(self, new_node):
self.right = new_node
def search_elem(self, key):
if self.key == key:
return self
if self.left is not None:
temp = self.left.search_elem(key)
if temp is not None:
return temp
if self.right is not None:
temp = self.right.search_elem(key)
return temp
return None
def print_left_part(self):
if self.left is not None:
self.left.inorder_traversal()
my_instance = None
print('Menu (this assumes no duplicate keys)')
print('insert <data> at root')
print('insert <data> left of <data>')
print('insert <data> right of <data>')
print('left')
print('quit')
while True:
my_input = input('What operation would you do ? ').split()
operation = my_input[0].strip().lower()
if operation == 'insert':
data = int(my_input[1])
new_node = BinaryTree_struct(data)
suboperation = my_input[2].strip().lower()
if suboperation == 'at':
my_instance = new_node
else:
position = my_input[4].strip().lower()
key = int(position)
ref_node = None
if my_instance is not None:
ref_node = my_instance.search_elem(key)
if ref_node is None:
print('No such key')
continue
if suboperation == 'left':
ref_node.insert_at_left(new_node)
elif suboperation == 'right':
ref_node.insert_at_right(new_node)
elif operation == 'left':
print('Nodes of the left subtree are : ', end='')
if my_instance is not None:
my_instance.print_left_part()
print()
elif operation == 'quit':
break输出
Menu (this assumes no duplicate keys) insert <data> at root insert <data> left of <data> insert <data> right of <data> left quit What operation would you do ? insert 5 at root What operation would you do ? insert 6 left of 5 What operation would you do ? insert 8 right of 5 What operation would you do ? left Nodes of the left subtree are : 6 What operation would you do ? quit Use quit() or Ctrl-D (i.e. EOF) to exit
解释
创建具有所需属性的“BinaryTree_struct”类。
它有一个“init”函数,用于将左节点和右节点赋值为“None”。
定义了一个“set_root”方法,用于设置二叉树的根值。
它有一个“insert_at_right”方法,用于将元素添加到树的右节点。
它有一个“insert_at_left”方法,用于将元素添加到树的左节点。
另一个名为“inorder_traversal”的方法,执行中序遍历。
定义了一个名为“search_elem”的方法,用于搜索特定元素。
定义了另一个名为“print_left_part”的方法,用于在控制台上仅显示二叉树的左侧部分。
创建一个实例并将其赋值为“None”。
获取用户输入以执行需要执行的操作。
根据用户的选择执行操作。• 在控制台上显示相关输出。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP