Python程式:查詢樹的中序遍歷中的第N個節點
當需要查詢二叉樹中序遍歷的第'n'個節點時,會建立一個包含設定根元素、向左或右新增元素、執行中序遍歷等方法的二叉樹類。建立類的例項後,即可用於訪問這些方法。
下面是相同的演示:
示例
class BinaryTree_struct:
def __init__(self, key=None):
self.key = key
self.left = None
self.right = None
def set_root(self, key):
self.key = key
def inorder_nth(self, n):
return self.inorder_nth_helper_fun(n, [])
def inorder_nth_helper_fun(self, n, in_ord):
if self.left is not None:
temp = self.left.inorder_nth_helper_fun(n, in_ord)
if temp is not None:
return temp
in_ord.append(self)
if n == len(in_ord):
return self
if self.right is not None:
temp = self.right.inorder_nth_helper_fun(n, in_ord)
if temp is not None:
return temp
def insert_t0_left(self, new_node):
self.left = new_node
def insert_to_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
btree_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('inorder ')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'insert':
data = int(do[1])
new_node = BinaryTree_struct(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
btree_instance = new_node
else:
position = do[4].strip().lower()
key = int(position)
ref_node = None
if btree_instance is not None:
ref_node = btree_instance.search_elem(key)
if ref_node is None:
print('No such key.')
continue
if suboperation == 'left':
ref_node.insert_t0_left(new_node)
elif suboperation == 'right':
ref_node.insert_to_right(new_node)
elif operation == 'inorder':
if btree_instance is not None:
index = int(do[1].strip().lower())
node = btree_instance.inorder_nth(index)
if node is not None:
print('nth term of inorder traversal: {}'.format(node.key))
else:
print('The index exceeds maximum possible index.')
else:
print('The tree is empty...')
elif operation == 'quit':
break輸出
Menu (this assumes no duplicate keys) insert <data> at root insert <data> left of <data> insert <data> right of <data> inorder quit What would you like to do? insert 5 at root What would you like to do? insert 6 left of 5 What would you like to do? insert 8 right of 5 What would you like to do? inorder 5 The index exceeds maximum possible index. What would you like to do? 6 6
解釋
建立具有所需屬性的'BinaryTree_struct'類。
它有一個'init'函式,用於將左節點和右節點設定為'None'。
它有一個'set_root'方法,用於設定二叉樹的根。
另一個名為'inorder_nth'的方法使用遞迴執行中序遍歷。
因此,它同時定義了一個輔助函式。
定義了另一個名為'insert_to_right'的方法,用於幫助將元素新增到根節點的右側。
定義了一個名為'insert_to_left'的方法,用於幫助將元素新增到根節點的左側。
定義了一個名為'search_elem'的方法,用於幫助搜尋特定元素。
建立'BinaryTree_struct'類的物件。
獲取使用者輸入,以確定需要執行的操作。
根據使用者的選擇,執行操作。
在控制檯上顯示相關的輸出。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP