日期:2014-05-20  浏览次数:20776 次

用二叉树实现表达式求值Java实现的问题?
我想用二叉树实现表达式求值
下面是节点Node类
[code=Java][/code]public class Node{
protected char key;
protected Node left;
protected Node right;

public Node(){
key = '0';
left = right = null;
}


public Node(char ch){
key = ch;
left = null;
right = null;
}

public Node(char ch, Node left, Node right){
key = ch;
this.left = left;
this.right = right;
}
}
下面是Tree类
[code=Java][/code]public class Tree {
private Node node = new Node();

public Tree(){
node.key = 0;
node.left = null;
node.right = null;
}

public static boolean isPlus(char ch){
if(ch=='+' || ch=='-')
return true;
return false;
}

public static boolean isMultiply(char ch){
if(ch=='*' || ch=='/')
return true;
return false;
}

public Node creatTree(String str, int i, int j){
int k,pos = 0;
int flag = 0;

if(i == j){
node.key = str.charAt(i);
node.left = null;
node.right = null;
}

for(k=i; k<=j; k++)
if(isPlus(str.charAt(k))){
++ flag;
pos = k;
}

if(flag == 0){
for(k=i; k<=j; k++)
if(isMultiply(str.charAt(k))){
++ flag;
pos = k;
}
}

if(flag != 0){
node.key = str.charAt(pos);
node.left = creatTree(str, i, pos-1);
node.right = creatTree(str, pos+1, j);
return node;
}
else 
return null;
}

double calculate(Node node){
double n1,n2;
if(node == null){
return 0;
}

System.out.println(node.left == null);
System.out.println(node.right == null);

if(node.left == null && node.right == null){
return (node.key-'0');
}

n1 = calculate(node.left);
n2 = calculate(node.right);

switch(node.key){
case '+':
return n1+n2;
case '-':
return n1-n2;
case '*':
return n1*n2;
case '/':
return n1/n2;
}
return 0;
}




}
下面是测试类:
[code=Java][/code]
public class Test {
public static void main(String []args){
Tree tree = new Tree();
String str = new String("1");
Node node = new Node(tree.creatTree(str, 0, str.length()-1).key,
tree.creatTree(str, 0, str.length()-1).left,tree.creatTree(str, 0, str.length()-1).right);

System.out.println(node.left == null);
System.out.println(tree.calculate(node));
}


}
为什么总是报Exception in thread "main" java.lang.NullPointerException
at Test.main(Test.java:6)的错误啊,,求改正,,,在线等,,,,,

------解决方案--------------------
应该是tree.creatTree(str, 0, str.length()-1)==null
------解决方案--------------------
你的left,right,key都是空的