fin arbre

This commit is contained in:
2024-11-27 12:26:48 +01:00
parent d6a9265998
commit 85103a2222
53 changed files with 1412 additions and 239 deletions

Binary file not shown.

View File

@@ -0,0 +1,45 @@
import java.util.ArrayDeque;
import java.util.Deque;
public class Infixe {
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("Veuillez fournir une expression en notation polonaise inversée.");
return;
}
Deque<Node> stack = new ArrayDeque<>();
try {
for (String token : args) {
switch (token) {
case "+":
case "-":
case "x":
case "/":
// Création d'un nœud opérateur
Node right = stack.pop();
Node left = stack.pop();
stack.push(new OperatorNode(token.equals("x") ? "*" : token, left, right));
break;
default:
// Création d'un nœud opérande
stack.push(new OperandNode(Integer.parseInt(token)));
break;
}
}
// Le résultat final doit être le seul élément restant sur la pile
if (stack.size() == 1) {
Node result = stack.pop();
System.out.println("= " + result.toInfix());
} else {
System.out.println("Erreur : Expression incorrecte.");
}
} catch (Exception e) {
System.out.println("Erreur lors de l'évaluation de l'expression : " + e.getMessage());
}
}
}

Binary file not shown.

View File

@@ -0,0 +1,4 @@
// Classe représentant un nœud de l'arbre de syntaxe
public abstract class Node {
public abstract String toInfix(); // Convertir en notation préfixe
}

Binary file not shown.

View File

@@ -0,0 +1,12 @@
public class OperandNode extends Node {
int value;
OperandNode(int value) {
this.value = value;
}
@Override
public String toInfix() {
return Integer.toString(value);
}
}

Binary file not shown.

View File

@@ -0,0 +1,20 @@
// Nœud opérateur
public class OperatorNode extends Node {
String operator;
Node left, right;
OperatorNode(String operator, Node left, Node right) {
this.operator = operator;
this.left = left;
this.right = right;
}
@Override
public String toInfix() {
// On ajoute systématiquement des parenthèses autour de chaque opération
if (operator == "*"){
return "(" + left.toInfix() + " x " + right.toInfix() + ")";
}
return "(" + left.toInfix() + " " + operator + " " + right.toInfix() + ")";
}
}