Создайте двоичное дерево из постфиксного выражения

1

Скажем, у меня есть следующее постфиксное выражение: 5372- * -

Я хочу создать двоичное дерево из этого выражения. Мой алгоритм: если мой char - это число, помещаем его в стек, если это оператор, выталкиваем два элемента из стека и делаем их дочерними элементами оператора. Затем нажмите оператор в стек. Кажется, что он работает, но я не могу связать маленькие деревья, которые я создаю.

Мой текущий код:

public void myInsert(char ch, Stack s) {
    if (Character.isDigit(ch)) // initial cond.
        s.push(ch);
    else {
        TreeNode tParent = new TreeNode(ch);
        TreeNode t = new TreeNode(s.pop());
        TreeNode t2 = new TreeNode(s.pop());
        tParent.right = t;
        tParent.left = t2;
        s.push(ch);
        System.out.println("par" + tParent.ch);
        System.out.println("cright" + tParent.right.ch);
        System.out.println("cleft" + tParent.left.ch);
    }
}

Мой тестовый класс:

Stack stree = new Stack();

    BST b = new BST();
    String str = "5-3*(7-2)";
    String postfix = b.convertToPosFix(str);
    System.out.println(postfix);

    for (char ch : postfix.toCharArray()) {
         b.myInsert(ch, stree);

    }

Мой выход:

par-
cright2
cleft7
par*
cright-
cleft3
par-
cright*
cleft5
Теги:
tree
binary-tree
infix-notation

1 ответ

1
Лучший ответ

Используйте Stack of TreeNode s, а не Stack of chars. Вы должны комбинировать TreeNode а не char s:

public void myInsert(char ch, Stack<TreeNode> s) {
    if (Character.isDigit(ch)) {
        // leaf (literal)
        s.push(new TreeNode(ch));
    } else {
        // operator node
        TreeNode tParent = new TreeNode(ch);

        // add operands
        tParent.right = s.pop();
        tParent.left = s.pop();

        // push result to operand stack
        s.push(tParent);
    }
}

TreeNode

public class TreeNode {
    public TreeNode right = null;
    public TreeNode left = null;
    public final char ch;

    TreeNode(char ch) {
        this.ch = ch;
    }

    @Override
    public String toString() {
        return (right == null && left == null) ? Character.toString(ch) : "(" + left.toString()+ ch + right.toString() + ")";
    }

}

главный

public static TreeNode postfixToTree(String s) {
    Stack<TreeNode> stree = new Stack<>();

    BST b = new BST();
    for (char ch : s.toCharArray()) {
        b.myInsert(ch, stree);
    }
    return stree.pop();
}

public static void main(String[] args) {
    System.out.println(postfixToTree("5372-*-"));
    System.out.println(postfixToTree("512+4*+3−"));
    System.out.println(postfixToTree("51*24*+"));
}

Это напечатает

(5-(3*(7-2)))
((5+((1+2)*4))−3)
((5*1)+(2*4))

Ещё вопросы

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