用二叉树实现表达式求值Java实现的问题?

Crack 2012-04-25 04:08:11
我想用二叉树实现表达式求值
下面是节点Node类
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类
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;
}




}
下面是测试类:

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)的错误啊,,求改正,,,在线等,,,,,
...全文
260 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
24K純帥 2012-04-26
  • 打赏
  • 举报
回复
你的left,right,key都是空的
Crack 2012-04-26
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 的回复:]

你的left,right,key都是空的
[/Quote]
怎么改呢?
cseu 2012-04-25
  • 打赏
  • 举报
回复
应该是tree.creatTree(str, 0, str.length()-1)==null

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧