将String转换为二叉树

时间:2014-06-16 12:53:47

标签: java algorithm graph graph-algorithm jung2

我遇到了可视化此字符串的问题:

"=IF(A2=1;0;IF(D2=D3;IF(C2=1;TRUE;FALSE);4))";

正如您所看到的,一般语法类似于excel公式,因此我有IF(TEST; TRUE; FALSE)

我的问题是我想用二进制搜索树格式使用库JUNG2来隐藏这个字符串。您可以在下面看到树的外观示例:

enter image description here

这是一些可视化顶点的代码。

public class SimpleGraphView {
    Graph<Integer, String> g;
    Graph<String, String> n;

    /** Creates a new instance of SimpleGraphView */

    String text = "=IF(A2=1;0;IF(D2=D3;IF(C2=1;TRUE;FALSE);4))";


    public SimpleGraphView() {

        n = new SparseMultigraph<String, String>();

        String str = text;
        String delim = ";";
        StringTokenizer tok = new StringTokenizer(str, delim, true);

        text = text.replace("(", " ");
        String s = text.replace(")", " ");
        String[] r = s.split(";");

        for (int i = 0; i < r.length; i++) {

            //Vertex
            if(r.equals("=IF(")) {
                n.addVertex(r[i].toString());
            }

            if(i % 2==0){
                n.addVertex(r[i].toString());
            } else {
                n.addVertex(r[i].toString());
            }

        }

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        SimpleGraphView sgv = new SimpleGraphView(); // Creates the graph...
        // Layout<V, E>, VisualizationViewer<V,E>
        Layout<Integer, String> layout = new CircleLayout(sgv.n);
        layout.setSize(new Dimension(300,300));

        VisualizationViewer<Integer,String> vv = new VisualizationViewer<Integer,String>(layout);
        vv.setPreferredSize(new Dimension(350,350));
        // Show vertex and edge labels
        vv.getRenderContext().setVertexLabelTransformer(new ToStringLabeller());
        vv.getRenderContext().setEdgeLabelTransformer(new ToStringLabeller());

        // Create our "custom" mouse here. We start with a PluggableGraphMouse
        // Then add the plugins you desire.
        PluggableGraphMouse gm = new PluggableGraphMouse(); 
        gm.add(new TranslatingGraphMousePlugin(MouseEvent.BUTTON1_MASK));
        gm.add(new ScalingGraphMousePlugin(new CrossoverScalingControl(), 0, 1.1f, 0.9f));

        vv.setGraphMouse(gm); 
        JFrame frame = new JFrame("Interactive Graph View 3");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().add(vv);
        frame.pack();
        frame.setVisible(true);       


    }
}

我可以渲染数组r中字符串的所有顶点。我的问题是我不知道如何将所有这些顶点与正确的边连接起来。任何建议,如何连接所有顶点与右边缘?

我非常感谢你的回答!

2 个答案:

答案 0 :(得分:2)

最简单的方法是以我认为的不同方式拆分文本。请注意,我用addEdgeaddVertex替换了图表的方法:

String[] operands = text.substring(1, text.length()).split("[;()]+");
int numIfs = operands.length / 3; // actually (operands.length - 1) / 3 but int division makes it the same 
String[] nodes = new String[numIfs]; // stores the nodes (test strings)
int[] operandNos = new int[numIfs]; // stores the number of operands the if currently has
int nodesIndex = -1; // the index of the if node currently parsed
for (String s : operands) {
    if (s.equals("IF")) {
        // new if found -> increase position in the "stack" (nodes)
        operandNos[++nodesIndex] = 0;
    } else {
        addVertex(s);
        switch (operandNos[nodesIndex]++) {
            case 0:
                // first operand = node name
                nodes[nodesIndex] = s;
                break;
            case 1:
                // second operand found -> add edge
                addEdge(s, nodes[nodesIndex]);
                break;
            case 2:
                // last operand found -> add edge and go back
                do {
                    addEdge(s, nodes[nodesIndex]);
                    s = nodes[nodesIndex--];
                } while (nodesIndex >= 0 && operandNos[nodesIndex]++ == 2);
                if (nodesIndex >= 0) {
                    // was not the last operand of the IF
                    addEdge(s, nodes[nodesIndex]);
                }
        }
    }
}

而不是addEdgeaddVertex使用图表的方法。我建议使用DirectedSparseGraph,因为图表是定向的,不允许平行边缘。要向图表添加顶点,请使用graph.addVertex(vertexName)并添加边使用graph.addEdge(edge, sourceVertexName, destinationVertexName)

addEdgeaddVertex的实现将如下所示:

void addVertex(String s) {
    n.addVertex(s);
}

void addEdge(String source, String dest) {
    n.addEdge("", source, dest);
}

或更好内嵌

答案 1 :(得分:0)

当您循环遍历String时,您需要跟踪哪个节点是父节点,哪个节点是子节点。输入“IF =”条件时,即父节点。其他人是它的孩子,直到你遇到下一个“IF =”条件(该节点也是前一个父节点的子节点,但是所有后续节点的父节点)。因此,将子级和父级添加到Pair,并将其添加到SimpleMultiGraph EdgeType.DIRECTED。关于有向边如何与Pair交互的文档有点不清楚,但我假设你添加到Vertex的第一个Pair是传出的,第二个是传入的。只是猜测,因为文档不清楚。