构建二叉树

Building a Binary Tree

每次循环时,我都会将一个表达式构建到二叉树中,在“)”的每个结尾创建一棵新树,并将那些 operators/operands 推入一个堆栈,然后弹回到一个完整的堆栈中二叉树.

我的构建方法:

package lab5;

import net.datastructures.*;

public class Expression<T> {

/** Contain Linked Tree and Linked Stack instance variables **/
LinkedBinaryTree<T> tree;
LinkedStack<LinkedBinaryTree<T>> stack;


public Expression () {
    tree = new LinkedBinaryTree<T> ();
    stack = new LinkedStack<LinkedBinaryTree<T>>();

} // end constructor

public LinkedBinaryTree<T> buildExpression (String expression) {// LinkedBinaryTree<T> is a type of LinkedBinaryTree
    // major TODO to implement the algorithm]
    LinkedBinaryTree<T> operand, op1, op2;
    LinkedStack<LinkedBinaryTree<T>> newStack = new LinkedStack<LinkedBinaryTree<T>>();
    String symbol;

    int i = 0;
    int len = expression.length();

    for (i = 0; i < len; i++) {
        symbol = expression.substring(i, i+1);

        if ((!symbol.equals ("(")) && (!symbol.equals (")"))) {
            operand = new LinkedBinaryTree<T> ();
            operand.addRoot((T)symbol);
            newStack.push(operand);
        } else if (symbol.equals ("(")){
            continue;
        } else {
            op2 = newStack.pop();
            operand = newStack.pop();
            op1 = newStack.pop();
        tree.attach(operand.root(), op1, op2);
        newStack.push(tree);
        }
    }
    tree = newStack.pop();
    return tree;

}  // end method buildExpression

}

我的测试:

package lab5;
import net.datastructures.*;

public class ExpressionTest {

/**
 * @param args
 * @throws EmptyTreeException
 */

/** Paranthesize is code fragment 8.26 pg. 346 **/

/** evaluateExpression method apart of LinkedBinaryTree class in net.datastructures **/

public static void main(String[] args) {
    // declare local variables/objects
            String s = new String ();
            String exp = "((((3+1)x3)/((9-5)+2))-((3x(7-4))+6))"; //-13
            Expression<String> expression = new Expression<String> ();

            // print the expression string
            System.out.printf ("The original Expression String generated via printf: %s", exp);

            // create the tree using the 'stub' method
            // i.e. it does nothing
            LinkedBinaryTree<String> tree = expression.buildExpression (exp);

            // use Object.toString simply to print its reference
            System.out.printf ("\n\nThe Tree: %s\n", tree);

    }

}

我收到 NullPointerException,我不知道为什么。我是否需要 'Try' 然后让错误通过?

该错误可能与检查 '('(单引号)而不是 symbol.equals ('(') 中的 "("(双引号)有关。您将一个字符串与一个字符进行比较,它们永远不会相等。

也许stack也没有初始化?它应该在 buildExpression().

本地

请注意,您的代码片段无法编译:

  • stack 未定义
  • symbol 未定义

顺便说一句:buildExpression() 可以是静态的,这样可以避免在 main 中分配空的未使用表达式。

首先检查 "(" 将避免检查 "(" 两次。