根据数学表达式建立表达式树
对于数学表达式a+b*(c-d)-e/f,可以表示成如下图所示的二叉树,
要建立二叉表达式树,方法有很多,下面介绍一种:找到最后计算的运算符,然后递归处理。
对于最后计算的运算符,+ -号在* /号之后计算,而对于相同优先级的运算符(+和-,*和/),我们规定最右出现的后计算(也可按其他顺序设计程序)。
输入数学表达式,然后输出后缀表达式。
样例输入:
a+b*(c-d)-e/f
样例输出:
abcd-*+ef/-
import java.util.Scanner;
class Node{
char val;
Node left;
Node right;
public Node(char val){
this.val=val;
}
}
public class Main {
public static Node buildTree(String str){
Node node=null;
if(str.length()==1){
node=new Node(str.charAt(0));
return node;
}
int p=0,c1=-1,c2=-1; //p,c1,c2分别存放未匹配的括号数量,最右出现的+-号下标,最右出现的*/号下标
for(int i=0;i<str.length();i++){
switch(str.charAt(i)){
case '(':
p++;
break;
case ')':
p--;
break;
case '+': case'-':
if(p==0)
c1=i;
break;
case '*': case'/':
if(p==0)
c2=i;
break;
}
}
if(c1<0&&c2<0) //整个表达式是被一对括号括起来的
node=buildTree(str.substring(1, str.length()-1));
else if(c1>0){
node=new Node(str.charAt(c1));
node.left=buildTree(str.substring(0,c1));
node.right=buildTree(str.substring(c1+1,str.length()));
}else{
node=new Node(str.charAt(c2));
node.left=buildTree(str.substring(0,c2));
node.right=buildTree(str.substring(c2+1,str.length()));
}
return node;
}
public static void postOrder(Node node){
if(node==null)
return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.val);
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String str=scanner.nextLine();
Node root=buildTree(str);
postOrder(root);
System.out.println();
}
scanner.close();
}
}
根据后缀表达式建立表达式树
输入后缀表达式,然后输出前缀表达式和中缀表达式。
样例输入:
abcd-*+ef/-
样例输出:
-+a*b-cd/ef
a+b*c-d-e/f
import java.util.Scanner;
import java.util.Stack;
class Node{
char val;
Node left;
Node right;
public Node(char val){
this.val=val;
}
}
public class Main {
public static Node buildTree(String str){
Stack<Node> stack=new Stack<Node>();
for(char c:str.toCharArray()){
if(c=='+'||c=='-'||c=='*'||c=='/'){
Node node=new Node(c);
Node right=stack.pop();
Node left=stack.pop();
node.left=left;
node.right=right;
stack.push(node);
}else{
Node node=new Node(c);
stack.push(node);
}
}
Node root=stack.pop();
return root;
}
public static void preOrder(Node node){
if(node==null)
return;
System.out.print(node.val);
preOrder(node.left);
preOrder(node.right);
}
public static void inOrder(Node node){
if(node==null)
return;
inOrder(node.left);
System.out.print(node.val);
inOrder(node.right);
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
while(scanner.hasNext()){
String str=scanner.nextLine();
Node root=buildTree(str);
preOrder(root);
System.out.println();
inOrder(root);
System.out.println();
}
scanner.close();
}
}