Формирование дерева из выражения

2

Вопрос: Дерево
может быть представлено строковым выражением в скобках
(Д (Б (А) (С)) (Е() (F (G() (Н)))))
Примечание: фигурные скобки, не содержащие значения, как в() в выражении выше, указывают нулевой дочерний указатель, как влево, так и вправо, в зависимости от расположения символа.

Это то, что я до сих пор

static public Stack list = new Stack();
        static void Main(string[] args)
        {

            //ArrayList list = new ArrayList();
            StreamReader RW = new StreamReader("Trees.txt");
            //Stack checkList = new Stack();
            while(!RW.EndOfStream)
            {
                string tmp = RW.ReadLine();
                BTNode T = null;
                doTree(tmp, 0, ref T);
                //doTree(tmp, T, 0, null, checkList);
                //list.Add(T);


            }
        }
        static private void doTree(string str,int num, ref BTNode T)
        {
            if(num>=str.Length)
            {
                return;
            }

            if (str[num] == '(')
            {
                if (num == 0)
                {
                    T = new BTNode(str[num + 1]);

                    list.Push(T);
                    doTree(str, num + 2, ref T);
                }
                else if ((str[num + 1] != ')')&&(str[num+3]!='('))
                {
                    BTNode temp = new BTNode(str[num + 1]);
                    T.setLeft(temp);
                    temp.setParent(T);
                    list.Push(temp);
                    doTree(str, num + 2, ref temp);
                }
                else
                {
                    doTree(str, num + 1,ref T);


                }
            }
            else if ((((str[num] == ')'))&&(str[num+2]!=')')))
            {


                BTNode par = (BTNode)list.Pop();
                BTNode temp = new BTNode(str[num +2]);
                par.setRight(temp);
                temp.setParent(par);
                doTree(str, num + 4, ref temp);
            }
            else
            {
                doTree(str, num + 6, ref T);
                list.Pop();
            }


        }

Может кто-то помочь

Теги:
tree
binary-tree

1 ответ

0

Что-то вроде этого:

public static class Node {

    String value;
    Node[] children = null;
}

// Recursive method getTree
// s is the binary-tree expresion.
// index[0] is the curren position to build the tree.
public static Node getTree(String s, int[] index) { 
    int i = index[0] + 1;
    if (s.length() <= i || s.charAt(i) == ')') {
        // empty node found
        index[0]+=2;
        return null;
    };
    Node n = new Node();
    char c = s.charAt(i);
    while (i < s.length()) {
        c = s.charAt(i);
        if (c == '(' || c == ')'){
            break;
        }
        i++;
    } 
    // this found the end of value to get it.
    n.value = s.substring(index[0] + 1, i);
    // increment index to next child or end node definition.
    index[0] = i;
    if (c == '(') {// the current node has children
        n.children = new Node[2];
        n.children[0] = getTree(s, index);
        n.children[1] = getTree(s, index);
    }
    // increment index for the last ')'
    index[0]++;
    return n;
}

Используй это:

public static void main(String[] args) {
    String s = "(D(B(A)(C))(E()(F(G)(H)))))";
    Node n = getTree(s, new int[]{0});
    System.out.println(n);
}

Узел с переопределенным методом toString:

public static class Node {
    ...
    public String toString() {
        if (children == null){
            return "(" + value + ")";
        }
        return "(" + value + (children[0] == null ? "()" : children[0].toString()) + (children[1] == null ? "()" : children[1].toString()) + ")";
    }
}

Он печатает:

(D(B(A)(C))(E()(F(G)(H))))

Ещё вопросы

Сообщество Overcoder
Наверх
Меню