forked from krish-ag/HacktoberFest22-Repo-DSA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
JavaExpressionTree.java
57 lines (48 loc) · 1.29 KB
/
JavaExpressionTree.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import java.util.Stack;
class Node{
char data;
Node left,right;
public Node(char data){
this.data = data;
left = right = null;
}
}
public class Main {
public static boolean isOperator(char ch){
if(ch=='+' || ch=='-'|| ch=='*' || ch=='/' || ch=='^'){
return true;
}
return false;
}
public static Node expressionTree(String postfix){
Stack<Node> st = new Stack<Node>();
Node t1,t2,temp;
for(int i=0;i<postfix.length();i++){
if(!isOperator(postfix.charAt(i))){
temp = new Node(postfix.charAt(i));
st.push(temp);
}
else{
temp = new Node(postfix.charAt(i));
t1 = st.pop();
t2 = st.pop();
temp.left = t2;
temp.right = t1;
st.push(temp);
}
}
temp = st.pop();
return temp;
}
public static void inorder(Node root){
if(root==null) return;
inorder(root.left);
System.out.print(root.data);
inorder(root.right);
}
public static void main(String[] args) {
String postfix = "ABC*+D/";
Node r = expressionTree(postfix);
inorder(r);
}
}