在 Python 中查找 n 元树的根的程序
假设,我们在一个数组中给出了一个 n 叉树的节点。我们必须通过重构来找到并返回树的根节点。必须从返回的节点以预序符号显示完整的树。
所以,如果输入是这样的
那么输出将是
[14, 27, 32, 42, 56, 65]
我们将使用树的根来显示树的前序遍历。因此,输出是树的前序遍历。
示例(Python)
让我们看看以下实现以获得更好的理解 -
import collectionsclass 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(tree):
indegree = collections.defaultdict(int)
for node in tree:
for child in node.children:
indegree[child.val] += 1
for node in tree:
if indegree[node.val] == 0:
return node
return None
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])
tree = [node2, node1, node5, node3, node6, node4]
root = solve(tree)
print(treeprint(root, None))
输入
node6 = Node(65)输出结果node5 = Node(56)
node4 = Node(42, [node5, node6])
node3 = Node(32)
node2 = Node(27)
node1 = Node(14, [node2, node3, node4])
tree = [node2, node1, node5, node3, node6, node4]
[14, 27, 32, 42, 56, 65]
以上是 在 Python 中查找 n 元树的根的程序 的全部内容, 来源链接: utcz.com/z/351635.html