如何打印所有可能的树python

时间:2017-09-17 20:41:39

标签: python tree traversal

我有一棵树,其中一个节点可能以两种或多种方式分支:

int main() {

    double operand1;
    double operand2;
    char operation;
    char more = 'y';
    double answer;

    while (more != 'n') {

        cout << "Enter an expression:""\n";
        cin >> operand1 >> operation >> operand2;

        switch (operation)
        {
        case '+':
            answer = (operand1 + operand2);
            break;

        case '-':
            answer = (operand1 - operand2);
            break;

        case '*':
            answer = (operand1 * operand2);
            break;

        case '/':
            answer = (operand1 / operand2);
            break;


        default:
            cout << "Not an operation :/";
            return 0;

        }

        cout << operand1 << operation << operand2 << "=" << answer << endl;
        cout << "Continue? (y/n) ";
        cin >> more;
    }
    return 0;
}

此处节点B可以具有分支 D和E ,或分支 X和Y 。 每个节点在python中表示为字典。例如。节点B = {0:节点,D和E作为分支,1:节点,X和Y作为分支}。

我的问题是:如何打印这两棵树?

到目前为止,我的程序首先打印A和B,然后打印D,E,F,G,然后打印X,Y,最后打印C.

我希望它完全打印第一棵树,如: A B D E F G C ,然后从头开始打印另一棵树 A B X Y C 。谁能帮我这个?我已经玩了一整天而没有任何进展。任何帮助是极大的赞赏。

以下是我的测试代码:

    A
   /  \
  B    C
 / \
D   E
   /  \
  F    G


    A
   / \
  B   C
 / \
X   Y

1 个答案:

答案 0 :(得分:0)

要生成所有的树组合,您可以遍历每个节点的可能子节点(存储在每个节点字典的整数键下),对每个子节点递归调用树构建方法,yielding返回结果:

首先,树设置:

def get_tree():
    X = {0: ('x', None, None), 'terminal':True}
    Y = {0: ('y', None, None), 'terminal':True}
    G = {0: ('g', None, None), 'terminal':True}
    F = {0: ('f', None, None), 'terminal':True}
    D = {0: ('d', None, None), 'terminal':True}
    C = {0: ('c', None, None), 'terminal':True}
    E = {0: ('e', F, G, False), 'terminal':False}
    B = {0: ('b', D, E, False), 1: ('b', X, Y, False), 'terminal':False}
    A = {0: ('a', B, C, False), 'terminal':False}
    return A

然后,生成所有树组合的函数:

from itertools import product
def get_trees(t):
   for a, b in t.items():
      if isinstance(a, int):
         v = [[b[0]], *[[i] if i is None else list(get_trees(i)) for i in b[1:3]]]
         yield from product(*v)

trees = list(get_trees(get_tree()))
for tree in trees:
   print(tree)

输出:

('a', ('b', ('d', None, None), ('e', ('f', None, None), ('g', None, None))), ('c', None, None))
('a', ('b', ('x', None, None), ('y', None, None)), ('c', None, None))