在 Python 中制作 n 元树副本的程序
假设,我们已经提供了一个 n 元树,它的根给了我们“根”。我们必须制作完整的 n 元二叉树的副本,并对两棵树进行预序遍历。复制的树必须使用另一个根节点存储。树的节点结构如下 -
Node:value : <integer>
children : <array>
所以,如果输入是这样的
,那么输出将是
[14, 27, 32, 42, 56, 65]
输入树和输出树的前序表示将与创建的树的精确副本相同。
示例(Python)
让我们看看以下实现以获得更好的理解 -
from queue import dequeclass Node:
def __init__(self, value, child = None) -> None:
self.val= value
self.children= []
if child != None:
for value in child:
self.children.append(value)
def solve(root):
if not root:
return root
head = Node(root.val)
q = deque([(root, head)])
while q:
node, cloned = q.popleft()
for chld in node.children:
new_n = Node(chld.val)
cloned.children.append(new_n)
q.append((chld,new_n))
return head
def treeprint(node, tree):
if node == None:
tree.append("None")
return tree
if tree == None:
tree = []
tree.append(node.val)
for child in node.children:
treeprint(child, tree)
return tree
node6 = Node(65)
node5 = Node(56)
node4 = Node(42, [node5, node6])
node3 = Node(32)
node2 = Node(27)
node1 = Node(14, [node2, node3, node4])
root = node1
copynode = solve(root)
print(treeprint(copynode, None))
输入
node6 = Node(65)输出结果node5 = Node(56)
node4 = Node(42, [node5, node6])
node3 = Node(32)
node2 = Node(27)
node1 = Node(14, [node2, node3, node4])
root = node1
[14, 27, 32, 42, 56, 65]
以上是 在 Python 中制作 n 元树副本的程序 的全部内容, 来源链接: utcz.com/z/317341.html