【问题标题】:tree algorithm to do calulation on leaves and get the value to the root ,python树算法对叶子进行计算并获取根的值,python
【发布时间】:2013-08-10 22:54:36
【问题描述】:

我有一棵树,我想遍历所有节点给它们一个值(score):

  • leaves nodes:该值是根据节点本身及其姐妹的属性计算得到的(只能在叶子节点上计算)
  • non leaf nodes: 他们从孩子那里获取分数,即比较叶子的孩子的分数并获得最高的分数 我可以弄清楚树的遍历,但我有点不知道如何根据前面列出的条件影响分数。

输入树:

((((a:1,((b:1,c:1)d:1,e:1)f:1)g:1,h:1,i:1)j:1,(k:1,l:1)m:1,(n:1,o:1,p:1)q:1)r:1)root;

遍历代码:

def trav_tree(n): 
       
    if not n.is_leaf():
        trav_tree(n.get_children()[0])
    sisters=[]
    sisters=n.get_sisters()
    print n.name,
    for sis in sisters:
        if not sis.is_leaf():
            trav_tree(sis.get_children()[0])
        print sis.name,

    n=t.get_tree_root() 
    trav_tree(n)

输出:

a b c d e f g h i j k l m n o p q r root

我应该做的是计算当我到达a我让我一直下去直到离开的姐妹,计算b和c的分数比我拿最高分给d,然后我就可以计算出a的分数等等...

解决这个问题的最佳方法是什么?
ps:我正在为树数据结构研究python ete2

在此先感谢

【问题讨论】:

    标签: algorithm python-2.7 data-structures recursion tree


    【解决方案1】:

    只需添加一个属性字段来表示每个非叶子节点的子节点的最高分数。

    然后进行根后遍历。

    【讨论】:

    • 我不明白这将如何帮助先初始化叶子,然后再获得价值?
    猜你喜欢
    • 2017-04-28
    • 2017-11-17
    • 1970-01-01
    • 2012-09-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-17
    • 2012-03-27
    • 1970-01-01
    相关资源
    最近更新 更多