2017-10-01 22 views
-1

트리의 루트가 연산자 "+"이고 피연산자/"children"이 3과 4이므로 테스트 클래스에서 첫 번째 테스트를 수행하는 것에 대해서만 걱정합니다. 루트가 "+" 왼쪽 자식 및 오른쪽 자식 노드를 스택에 밀어 넣습니다. Stack 클래스의 pop() 메서드를 사용할 수없는 이유를 이해하려고 시도합니다.누구나 내 evaulateExpression에서 pop()의 사용이 작동하지 않는 이유를 말해 줄 수 있습니까?

노드 클래스

public class Node <E> { 
E data; 
Node <E> left; 
Node <E> right; 

public Node(E data) { 
    this.data = data; 
} 

public Node(E data, Node <E> left, Node <E> right) { 
    this.data = data; 
    this.left = left; 
    this.right = right; 
} 

public String toString() { 
    return data.toString(); 
} 

} 

ExpressionTree 클래스 수입 java.util.Stack의;

public class ExpressionTree { 
Node <String> root; 

public void buildTree(String expression) { 
    Stack < Node <String>> s = new Stack < Node <String>>(); 

    String expArray[] = expression.split(" "); 
    for (String st: expArray) { 
    switch (st) { 
    case "+": 
    case "-": 
    case "*": 
    case "/": 
    Node <String> right = s.pop(); 
    s.push((new Node <String> (st, s.pop(), right))); 
    break; 
    default: 
    s.push(new Node <String> (st)); 


    } 
    } 

    root = s.pop(); 
} 

public void printExpression() { 
    printExpression(root); 
    System.out.println(); 
} 

private void printExpression(Node <String> n) { 
    if (n != null) { 
    printExpression(n.left); 
    System.out.print(n); 
    printExpression(n.right); 
    } 
} 

public int evaluateExpression() { 

    return evaluateExpression(root); 
} 

public int evaluateExpression(Node <String> n) { 
    Stack < Node <String>> s = new Stack < Node <String>>(); 
    n = root; 
    if (n == null) { 
    return 0; 
    } else { 
    if (n.data.equals("+")) { 
    s.pop(n.left); 
    s.pop(n.right); 
    s.push(n); 
    evaluateExpression(n); 
    } 
    } 
    return 0; 
} 

} 

코드 Stack API에서 볼 수 있듯이

s.pop(n.left); 
s.pop(n.right); 

의로 테스트 클래스

public class ExpressionTreeTest { 

public static void main(String[] args) { 
    ExpressionTree et = new ExpressionTree(); 
    et.buildTree("3 4 +"); //infix: 3 + 4 
    et.printExpression(); 
    System.out.println(et.evaluateExpression()); 

    /*et.buildTree("3 4 2 * 1 5 -/+"); //infix: 3+4*2/(1-5) 
    et.printExpression(); 
    System.out.println(et.evaluateExpression()); 

    et.buildTree("3 4 5 * 2/+"); //infix: 3+4*5/2 
    et.printExpression(); 
    System.out.println(et.evaluateExpression()); 

    et.buildTree("12 8 + 6 5 - * 3 2 - 2 3 + * /"); //infix: (12+8)*(6- 
    5)/((3-2)*(2+3)) 
    et.printExpression(); 
    System.out.println(et.evaluateExpression());*/ 


} 

} 
+0

이미 트리가있는 경우 왜'Stack'을 사용합니까? 또한,'evaluateExpression()'의'n = root;'는 인자의 값을 버린다. –

답변

1

, 팝업 기능은 매개 변수를 사용하지 않습니다.

""[r]이 스택의 맨 위에있는 객체를 제거하고이 객체를이 함수의 값으로 반환합니다. "

스택 맨 위에있는 특정 개체 대신 특정 개체를 제거하려면 다른 클래스를 사용해야합니다.