我想要创建一个树,用户给边(以u-v格式)和值。节点可以有任意数量的子节点。例如,如果给定3节点的值为2 3 4,而边为1-2和2-3,则树将为2 3 4,并且不需要u< v.And,边是无向的,所以我必须找到在根附近出现哪一种情况。
我尝试过一种代码,但是它不能像下面这样创建树,但是节点可以有任意数量的子节点
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.append(Node(a[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所以我不知道该怎么纠正。请提供正确的代码
发布于 2019-07-03 22:05:14
假设用户已经给出了如下的边缘列表
边=[ 3,2,3,4,4,5 ]
根=2
首先,,我们必须将边列表转换为一个适当的字典,它将指示给定边的树结构。下面是我在StackOverflow.上找到的代码
def createDict(edges, root):
graph ={}
for x,y in es:
graph.setdefault(x,set()).add(y)
graph.setdefault(y,set()).add(x)
tree, stack = {}, [s]
while stack:
parent = stack.pop()
children = graph[parent] - tree.keys()
tree[parent] = list(children)
stack.extend(children)
for i in tree.keys():
if tree[i] == []: #if the node is leaf node, give it a 0 val
tree[i].append(0)
return tree输出为: tree ={ 2: 3,3: 4,4: 5,5:}
现在,我们将使用类Node将其转化为一个树结构。这段代码是我写的。
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的专家,只是个初学者。更正和修改受到高度欢迎。
https://stackoverflow.com/questions/55648556
复制相似问题