【问题标题】:Iterative preorder k-ary tree traversal迭代前序k-ary树遍历
【发布时间】:2014-01-10 12:23:49
【问题描述】:

我的 python 代码当前打印出 k-ary 树中每个节点的名称,从根到叶。但是,我希望将子节点 > 1 的分支节点的名称打印 n 次;其中 n = 孩子的数量。

对于上面的树

我的代码打印以下内容

start
a
b
d
f
end
c
e
end
c
e
end

但是,我希望它打印以下内容

start
a
b
d
f
end
b
c
e
end
d
c
e
end

我希望节点 b 和 d 打印两次(以正确的顺序),因为它们有两个孩子。

我觉得这比我想象的要简单。我需要添加访问过的节点列表吗?但是我还需要知道访问的次数?

需要注意的是,只有具有 (n.tag == prefix + 'decision' 或 n.tag == prefix + 'task') 的节点才会有多个子节点。因此,我可以保留一个决策/任务节点列表以及它们被访问的次数。如果访问次数==子节点数,从列表中弹出节点?

我觉得我把这件事复杂化了很多。

这是一个简单的示例,但是我的代码需要适用于 k-ary。 (我知道我的示例树只是二叉树)。

我的代码如下:

from itertools import izip
import xml.etree.ElementTree as ET

def main():

    prefix = "{http://jbpm.org/4.4/jpdl}"

    xml = ET.parse("testWF2.xml")
    root = xml.getroot()
    i = root.findall('*')

    # convert list to dictionary indexed by Element.name
    temp = []
    for it in i:
        name = it.get("name")
        if (name):
            temp.append(name)
        else:
            tag = it.tag
            temp.append(tag.replace(prefix, '')) # if no name exists use tag (ex. start and end)
    b = dict(izip(temp, i)) # create the dictionary with key = name

    nodes = []
    # add root to the list
    nodes.append(b["start"])

    while(nodes):

        n = nodes.pop()
        transitions = n.findall(prefix+"transition")
        children = []
        # get all of n's children
        for t in transitions:
            children.append(b[t.get("to")])

        for child in children:
            nodes.append(child) # add child

        if (not n.get("name")):
            print ("start")
        else:
            print(n.get("name"))

    # end while loop

main()

如果有人需要查看 testWF2.xml 文件,请在此处粘贴 http://bpaste.net/show/160832/

【问题讨论】:

  • 感谢您提供足以使用它的 xml 文件和代码。顺便说一句,你为什么要双重列出父母?如果是为了消除歧义,您真的需要列出从根目录开始的整个路径,不是吗?

标签: python algorithm python-2.7 tree tree-traversal


【解决方案1】:

针对您的特殊要求,我对其进行了更改,以便每次迭代都适用于父级和子级。输出基于父级 - 这样父级自动输出 k 次。当没有其他孩子时,它还需要一个特殊情况来输出孩子。

from itertools import izip
import xml.etree.ElementTree as ET

def main():
    prefix = "{http://jbpm.org/4.4/jpdl}"

    xml = ET.parse("testWF2.xml")
    root = xml.getroot()
    i = root.findall('*')

    # convert list to dictionary indexed by Element.name
    temp = []
    for it in i:
        name = it.get("name")
        if name:
            temp.append(name)
        else:
            tag = it.tag
            temp.append(tag.replace(prefix, '')) # if no name exists use tag (ex. start and end)
    b = dict(izip(temp, i)) # create the dictionary with key = name


    nodes = []
    # add root to the list
    start_pair = (None, b["start"])  # # # # # using pairs
    nodes.append(start_pair)

    while(nodes):
        parent, n = nodes.pop()  # # # # # using pairs
        transitions = n.findall(prefix+"transition")
        children = []
        # get all of n's children
        for t in transitions:
            child = b[t.get("to")]
            children.append(child)
            nodes.append((n, child))  # add parent/child pair

        # only output the parent (thus outputing k times)
        try:
            print parent.get("name", "start")
        except AttributeError:
            pass  # ignore the start position
        # also output the node if it has no children (terminal node)
        if len(children) < 1:
            print n.get("name", "start")

    # end while loop

main()

start
a
b
d
f
end
d
c
e
end
b
c
e
end

【讨论】:

    【解决方案2】:

    这不是您在图表中显示的树。它是一个图表。您可以使用 DFS 打印出图表。将每次调用 DFS 的开始和结束节点更改为:

    1. 从头到尾
    2. b 结束
    3. 结束

    【讨论】:

      猜你喜欢
      • 2014-08-26
      • 1970-01-01
      • 2013-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-28
      • 2012-01-05
      相关资源
      最近更新 更多