在python中创建一个具有用户给定边的n元树
我想创建一个树,用户以u-v格式给出边和值。节点可以有任意数量的子节点。例如,如果3个节点的给定值为2 3 4,边为1-2和2-3,则树将 2. 3. 4. 也不需要u在python中创建一个具有用户给定边的n元树,python,tree,graph-theory,Python,Tree,Graph Theory,我想创建一个树,用户以u-v格式给出边和值。节点可以有任意数量的子节点。例如,如果3个节点的给定值为2 3 4,边为1-2和2-3,则树将 2. 3. 4. 也不需要u
2
3
4
5
下面是代码
class Node :
# Utility function to create a new tree node
def __init__(self ,key):
self.key = key
self.child = []
# Prints the n-ary tree level wise
def printNodeLevelWise(root):
if root is None:
return
# create a queue and enqueue root to it
queue = []
queue.append(root)
# Do level order traversal. Two loops are used
# to make sure that different levels are printed
# in different lines
while(len(queue) >0):
n = len(queue)
while(n > 0) :
# Dequeue an item from queue and print it
p = queue[0]
queue.pop(0)
print p.key,
# Enqueue all children of the dequeued item
for index, value in enumerate(p.child):
queue.append(value)
n -= 1
print "" # Seperator between levels
# test case
t = raw_input()
t=int(t)
while(t > 0):
# number of nodes
n = raw_input()
n=int(n)
# array to keep node value
a = []
nums = raw_input().split()
for i in nums: a.append(int(i))
n = n -1
root = Node(a[0])
i = 1
for j in range(0, n):
u, v = raw_input().split()
u=int(u)
v=int(v)
if(u == 1):
root.child.append(Node(a[i]))
else:
root.child[u-2].child.append(Node(a[i]))
i=i+1
t=t-1
printNodeLevelWise(root)
我知道应该在root.child[u-2].child.appendNodea[I]上进行更正
我希望输出是
2
3
4
5
对于这个案子,但我得到了
Traceback (most recent call last):
File "/home/25cd3bbcc1b79793984caf14f50e7550.py", line 52, in <module>
root.child[u-2].child.append(Node(a[i]))
IndexError: list index out of range
所以我不知道如何纠正它。请为我提供正确的代码假设用户已将边列表作为 边=[[3,2],[3,4],[4,5]] 根=2 首先,我们必须将边列表转换为适当的字典,该字典将指示给定边的树结构。下面是我在StackOverflow上找到的代码 输出将是:tree={2:[3],3:[4],4:[5],5:[0]} 现在,我们将使用类节点使其成为树结构。这段代码是我写的
class Node:
def __init__(self, val):
self.val = val
self.children = []
def createNode(tree, root,b=None, stack=None):
if stack is None:
stack = [] #stack to store children values
root = Node(root) #root node is created
b=root #it is stored in b variable
x = root.val # root.val = 2 for the first time
if len(tree[x])>0 : # check if there are children of the node exists or not
for i in range(len(tree[x])): #iterate through each child
y = Node(tree[x][i]) #create Node for every child
root.children.append(y) #append the child_node to its parent_node
stack.append(y) #store that child_node in stack
if y.val ==0: #if the child_node_val = 0 that is the parent = leaf_node
stack.pop() #pop the 0 value from the stack
if len(stack): #iterate through each child in stack
if len(stack)>=2: #if the stack length >2, pop from bottom-to-top
p=stack.pop(0) #store the popped val in p variable
else:
p = stack.pop() #pop the node top_to_bottom
createNode(tree, p,b,stack) # pass p to the function as parent_node
return b # return the main root pointer
在这段代码中,b只是一个指向根节点的变量,因此我们可以逐级遍历它并打印它
对于级别顺序打印:
def printLevel(node):
if node is None:
return
queue = []
queue.append(node)
while(len(queue)>0):
n =len(queue)
while(n>0):
p = queue[0]
queue.pop(0)
if p.val !=0: #for avoiding the printing of '0'
print(p.val, end=' ')
for ind, value in enumerate(p.children):
queue.append(value)
n -= 1
print(" ")
输出为:
2
3
4
5 #each level is getting printed
我现在不知道如何以倾斜的方式打印它:仍在处理它
嗯,我不是Python的专家,只是一个初学者。非常欢迎更正和修改。child[u-2]。这是引用列表中先前元素的困难部分。这就是为什么大多数树都是递归遍历的。此时,子元素必须少于2个元素。因此,你是出界的。要调试它,请打印root.child并检查结果。或者发布您正在使用的示例输入,以便我们可以运行代码。或者只是查找递归解决方案并保存您自己:我查找了一个递归解决方案,但它们都是针对二叉树或bst的。例如,括号中的下一行只是为了显示它们在不同的行中,我有1个下一行4下一行-5 6-3 2下一行1 2下一行23下一行3下一行检查:,这基本上是您的代码以及如何做您想要做的事情:您还可以尝试将树存储在defaultdict中,然后将其转换为JSON以获得漂亮的树视图
2
3
4
5 #each level is getting printed