【问题标题】:Implementing n-ary tree from a given set of inputs从给定的一组输入实现 n 叉树
【发布时间】:2019-12-10 23:52:00
【问题描述】:

我正在尝试从给定的输入创建一棵树。一个根将在那里,包括子节点和子子节点。我可以实现树,我可以在其中将子节点添加到特定的主节点(我已经知道根节点)。但是,我试图弄清楚实现树的推荐方法是什么,我们必须首先从给定的输入集中找到根节点。举个例子:

There are n lines,
Value in each line represent the master node of that line number.
4 ( n = 4, next n lines)

1 ( 1 is a master node of 1, here line number is 1)
1 (1 is a master node of 2, here line number is 2)
2 (2 is a master node of 3, here line number is 3)
1 (1 is a master node of 4, here line number is 4)

所以树应该是这样的,

   1
 / | 
2  4
|
3

在这里,我们可以看到根节点是1。但是在知道所有输入值之前,我们无法猜测根节点。在实现树之前,我应该先从输入中找出根节点吗?或者,还有其他方法吗?

下面的代码是在树中添加一个节点:

class Node : 

    # Utility function to create a new tree node 
    def __init__(self ,key): 
        self.key = key 
        self.child = [] 

def printNodeLevelWise(root): 
    if root is None: 
        return

    queue = [] 
    queue.append(root) 

    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 ("") 


root = Node(1) 
root.child.append(Node(2)) 
root.child.append(Node(4)) 
root.child[0].child.append(Node(3)) 
printNodeLevelWise(root) 

上面的代码将给出实现这棵树:

   1
 / | 
2  4
|
3

但是,从给定的输入中实现相同的推荐方法是什么?

【问题讨论】:

  • 阅读n后,您可以创建一个节点列表,键从1到n。然后,对于输入的每一行,读取主节点号,并更新child列表以包含当前行号对应的节点。
  • "master" 在树的上下文中是一个奇怪的词。你是说“父母”吗?那么为什么在这个例子中 1 是它自己的父母呢?那将是一个循环......
  • 有没有规定当一行有这样的自引用时,它必须是根?

标签: python algorithm data-structures tree binary-tree


【解决方案1】:

假设:

  • “主人”是指“父母”,而
  • 当一行有自引用时——例如 i 出现在主列表的第 i 行——它是根

...那么你可以这样继续:

nodes = {} # dictionary of all nodes keyed by their value
root = None
n = int(input()) # get the number of nodes

for linenum in range(1, n+1):
    parentnum = int(input()) # get the "master" for this line
    # create the involved nodes that do not yet exist:
    if not linenum in nodes:
        nodes[linenum] = Node(linenum)
    if not parentnum in nodes:
        nodes[parentnum] = Node(parentnum)
    if parentnum == linenum: # a self-reference indicates the root
        root = nodes[parentnum]
    else: # set the parent-child relationship
        nodes[parentnum].child.append(nodes[linenum])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-09-07
    • 1970-01-01
    • 2022-10-14
    • 2014-03-22
    • 2012-01-09
    • 1970-01-01
    • 2017-12-16
    • 1970-01-01
    相关资源
    最近更新 更多