ツリーを構築し、挿入、削除、表示を実行するPythonプログラム
二分木を構築し、要素の挿入、要素の削除、ツリーの要素の表示などの操作を実行する必要がある場合、クラスはその中にメソッドを使用して定義されます。クラスのインスタンスが定義され、これを使用して要素にアクセスし、操作を実行します。
以下は同じのデモンストレーションです-
例
class Tree_struct:
def __init__(self, data=None, parent=None):
self.key = data
self.children = []
self.parent = parent
def set_root(self, data):
self.key = data
def add_node(self, node):
self.children.append(node)
def search_node(self, key):
if self.key == key:
return self
for child in self.children:
temp = child.search_node(key)
if temp is not None:
return temp
return None
def remove_node(self):
parent = self.parent
index = parent.children.index(self)
parent.children.remove(self)
for child in reversed(self.children):
parent.children.insert(index, child)
child.parent = parent
def bfs(self):
queue = [self]
while queue != []:
popped = queue.pop(0)
for child in popped.children:
queue.append(child)
print(popped.key, end=' ')
my_instance = None
print('Menu (this assumes no duplicate keys)')
print('add <data> at root')
print('add <data> below <data>')
print('remove <data>')
print('display')
print('quit')
while True:
do = input('What would you like to do? ').split()
operation = do[0].strip().lower()
if operation == 'add':
data = int(do[1])
new_node = Tree_struct(data)
suboperation = do[2].strip().lower()
if suboperation == 'at':
my_instance = new_node
elif suboperation == 'below':
position = do[3].strip().lower()
key = int(position)
ref_node = None
if my_instance is not None:
ref_node = my_instance.search_node(key)
if ref_node is None:
print('No such key.')
continue
new_node.parent = ref_node
ref_node.add_node(new_node)
elif operation == 'remove':
data = int(do[1])
to_remove = my_instance.search_node(data)
if my_instance == to_remove:
if my_instance.children == []:
my_instance = None
else:
leaf = my_instance.children[0]
while leaf.children != []:
leaf = leaf.children[0]
leaf.parent.children.remove_node(leaf)
leaf.parent = None
leaf.children = my_instance.children
my_instance = leaf
else:
to_remove.remove_node()
elif operation == 'display':
if my_instance is not None:
print('Breadth First Search traversal is : ', end='')
my_instance.bfs()
print()
else:
print('The tree is empty')
elif operation == 'quit':
break 出力
Menu (this assumes no duplicate keys) add <data> at root add <data> below <data> remove <data> display quit What would you like to do? add 5 at root What would you like to do? add 6 below 5 What would you like to do? add 8 below 6 What would you like to do? remove 8 What would you like to do? display Breadth First Search traversal is : 5 6 What would you like to do? quit
説明
-
必要な属性を持つ「Tree_struct」クラスが作成されます。
-
空のリストを作成するために使用される「init」関数があります。
-
ツリーのルートを指定するために、「set_root」という名前の別のメソッドが定義されています。
-
ツリーにノードを追加するのに役立つ「add_node」という名前の別のメソッドが定義されています。
-
特定の要素の検索に役立つ「search_node」という名前の別のメソッドが定義されています。
-
ツリーから要素を削除する「remove_node」という名前のメソッドが定義されています。
-
「bfs」という名前の別のメソッドが定義されています。これは、ツリーで幅優先探索を実行するのに役立ちます。
-
インスタンスが作成され、「なし」に割り当てられます。
-
実行する必要のある操作に対してユーザー入力が行われます。
-
ユーザーの選択に応じて、操作が実行されます。
-
関連する出力がコンソールに表示されます。
-
Pythonの二分木ぬりえゲーム
二分木でターン制のゲームをプレイする2人のプレーヤーがいるとします。この二分木のルートとツリー内のノード数nがあります。ここで、nは奇数であり、各ノードには1からnまでの異なる値があります。最初に、最初のプレーヤーは値xに1 <=x <=nの名前を付け、2番目のプレーヤーは値yに1 <=y <=nの名前を付け、y!=xのような条件を保持します。最初のプレーヤーはノードを値xの赤で色付けし、2番目のプレーヤーはノードを値yの青で色付けします。その後、プレイヤーは最初のプレイヤーから順番に順番に進みます。各ターンで、プレーヤーは自分の色のノード(プレーヤー1の場合は赤、プレーヤー2の場合は青)を取
-
Pythonでの二分木の直径
二分木があるとしましょう。木の直径の長さを計算する必要があります。二分木の直径は、実際には、ツリー内の任意の2つのノード間の最長パスの長さです。このパスは必ずしもルートを通過する必要はありません。したがって、ツリーが以下のようになっている場合、パスの長さ[4,2,1,3]または[5,2,1,3]は3であるため、直径は3になります。 これを解決するには、次の手順に従います- dfsを使用して直径を見つけ、答えを設定します:=0 ルートdfs(root)を使用してdfs関数を呼び出します dfsは以下のdfs(node)のように機能します ノードが存在しない場合は、0を返します 左