我試圖遍歷一棵任意的樹并建立一棵新的樹,這將洗掉某些節點,但將它們的子節點連接到父節點。我不想使用遞回或類,只想使用串列、字典等。
下面的代碼完成了一半的作業--它遍歷了原來的樹,并試圖建立一個新的樹,但我實在無法用堆疊來建立一個新的樹。
original_tree = {
'id': 1,
'children': [
{
'id': 2,
'children': [{'id': 3}, {'id': 4}] 。
},
{
'id': 5,
'children': [
{'id': 6, 'children': [{'id': 7}]}。
{'id': 8, 'delete': True, 'children': [{'id': 9}, {'id': 10}]}。
{'id': 11}, {'id': 11}.
]
}
]
}
堆疊 = [original_tree]
new_tree = {}
while len(stack):
node = stack.pop(0)
print(node['id'] )
children = node.get('children', [] )
# ===開始建立一個新的樹 ===
if not node.get('delete') 。
new_tree['id'] = node['id']
pass] =節點['id']
# ================================
for i in range(len(children) - 1, -1, -1)。)
stack.insert(0, children[i])
uj5u.com熱心網友回復:
使用堆疊,你失去了父代和子代之間的聯系--沒有辦法知道你從堆疊中彈出的下一個專案是兄弟姐妹還是父代。你可以通過在向堆疊中添加專案時跟蹤父項來解決這個問題。然后當你從堆疊中彈出一個專案時,你就會有一個對父節點的參考。
為了處理洗掉,你只需要將被洗掉的孩子添加到堆疊中,并提供正確的父節點參考。這里有一個快速的例子:
original_tree = {
'id': 1,
'children': [
{
'id': 2,
'children': [{'id': 3}, {'id': 4}] 。
},
{
'id': 5,
'children': [
{'id': 6, 'children': [{'id': 7}]}。
{'id': 8, 'delete': True, 'children': [{'id': 9}, {'id': 10}]}。
{'id': 11}, {'id': 11}.
]
}
]
}
stack = [{'parent': None, 'node': original_tree}]
root = None[/span].
while len(stack):
frame = stack.pop()
node = frame['node']
parent = frame['parent']
# 分配一個新的節點 'id'/span>: node['id'/span>]}
# Append the node to the parent if there is one; there won't be one for the root
if parent is not None:
parent.setdefault('children', []).append(new_node)
else:
根 = new_node
children = node.get('children', [] )
print(node['id'])
for child in reversed(children)。
if child.get('delete') 。
# 要洗掉一個孩子,你需要把它的孩子加入堆疊。
grand_children = child.get('children', [] )
for grand_child in reversed(grand_children)。
stack.append({'parent': new_node, 'node': grand_child})
else:
stack.append({'parent': new_node, 'node': child})
列印新的樹root給你:
{'id': 1,
'children': [{'id': 2, 'children': [{'id': 3}, {'id': 4}]}。
{'id': 5,
'children': [{'id': 6, 'children': [{'id': 7}]}。
{'id': 9}。
{'id': 10}。
{'id': 11}]}。
其中被洗掉的節點8的孩子,現在是5的孩子。
(另外,對于 python 串列,從結尾處彈出并追加會更有效率。pop() & append() 而不是 insert(0) 和 pop(0))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/327331.html
標籤:
上一篇:如何傳遞引數并以所需格式輸出
