5+3*4的表达式树Java代码并将结果打印出来
时间: 2024-02-12 08:05:40 浏览: 56
拼接打印的JAVA代码
下面是一个 Java 代码实现 5+3*4 表达式树的构建和计算过程,并将结果打印出来:
```java
class TreeNode {
char val;
TreeNode left, right;
TreeNode(char val) {
this.val = val;
this.left = this.right = null;
}
}
public class ExpressionTree {
public int evaluateExpressionTree(TreeNode root) {
if (root == null) {
return 0;
}
if (root.left == null && root.right == null) {
return root.val - '0';
}
int leftSum = evaluateExpressionTree(root.left);
int rightSum = evaluateExpressionTree(root.right);
switch (root.val) {
case '+':
return leftSum + rightSum;
case '-':
return leftSum - rightSum;
case '*':
return leftSum * rightSum;
case '/':
return leftSum / rightSum;
default:
return 0;
}
}
public TreeNode buildExpressionTree(char[] postfix) {
Stack<TreeNode> stack = new Stack<>();
int n = postfix.length;
for (int i = 0; i < n; i++) {
char c = postfix[i];
if (isOperator(c)) {
TreeNode node = new TreeNode(c);
node.right = stack.pop();
node.left = stack.pop();
stack.push(node);
} else {
stack.push(new TreeNode(c));
}
}
return stack.pop();
}
private boolean isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
public static void main(String[] args) {
ExpressionTree tree = new ExpressionTree();
String postfix = "534*+";
TreeNode root = tree.buildExpressionTree(postfix.toCharArray());
int result = tree.evaluateExpressionTree(root);
System.out.println(result);
}
}
```
输出结果为 17,即 5 + 3 * 4 的计算结果。
阅读全文