遍历非二叉树

时间:2012-12-05 18:56:00

标签: python

我为节点制作了自定义类

class NodeTree(object):
    def __init__(self, name = None, children = None):
        self.name = name
        self.children = children

并定义了一个使树(包含其子节点的节点)的函数

def create_tree(d):
    x = NodeTree()
    for a in d.keys():
        if type(d[a]) == str:
            x.name = d[a]
        if type(d[a]) == list:
            if d[a] != []:
                for b in d[a]:
                    x.add_child(create_tree(b))
    return x

输入是一个dict,其中一个参数用于节点名称,另一个列表的子节点与父节点的格式相同。 该函数工作正常,我已经制作了证明它的方法,但我找不到一种方法来正确遍历它并获得树的高度。我不知道“高度”是否是正确的术语因为我知道这可能是矛盾的,我需要将节点计为度量单位,如下所示:

                                      parent
                                         |
                                         |
                                     ---------
                                     |       |
                                    child   child

这棵树的高度是2,我已经尝试了所有的东西,从班级的柜台到标签,一切似乎都堕落了,我从来没有得到正确的高度。 我应该怎么做?

1 个答案:

答案 0 :(得分:4)

为树创建一个递归height方法,用于确定节点的高度(即从该节点到叶子的路径中的最大节点数):

def height(self):
    if not self.children:  # base case
        return 1
    else:                  # recursive case
        return 1 + max(child.height() for child in self.children)

其他树遍历也可以递归完成。例如,这是一个生成器方法,它以“预先订购”的方式生成树节点的名称(即,每个父节点在其子节点和后代之前):

def preorder(self):
    yield self.name
    for child in self.children:
        yield from child.preorder() # Python 3.3 only!

该循环中的yield from语法是Python 3.3中的新增功能。您可以在早期版本中获得相同的结果:

        for descendent in child.preorder():
            yield descendent