概念
用来表示表达式的树叫表达式树,在表达式树中,叶子节点是操作数,而非叶子节点是操作符,也就是说,表达式树是一个内部节点为操作符,叶子节点为操作树的二叉树,
代码
BinaryTreeNode buildExprTree(char postFixExpr[],int size){
LLStack s = new llStack();
for(int i = 0;i<size;i++){
if(isOperand(postFixExpr[i])){
BinaryTreeNode node = new BinaryTreeNode();
if(node == null){
System.out.println("Out of memory!");
return null;
}
node.setData(postFixExpr[i]);
node.setLeft(null);
node.setRight(null);
s.push(node);
}
else{
BinaryTreeNode t2 = s.pop();
BinaryTreeNode t1 = s.pop();
BinaryTreeNode newNode = new BinaryTreeNode();
if(newNode == null){
System.out.println("Out of memory!");
}
newNode.setData(postFixExpr[i]);
newNode.setLeft(t1);
newNode.setRight(t2);
s.push(newNode);
}
}
}
boolean isOperand(char c){
if(c == '+' || c== '-' || c=='*' || c=='/'){
return false;
}
return true;
}