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