gpt4 book ai didi

java - 我现在如何使用扫描仪 "build"树? (代码后有说明)

转载 作者:行者123 更新时间:2023-12-02 06:27:34 25 4
gpt4 key购买 nike

该作业旨在帮助理解和练习树概念和遍历。我应该使用树来评估前缀(抛光)表示法中的表达式,以及打印后缀(反向抛光)表示法和中缀表示法中的表达式。

这是给出的评估类(class)。

 import java.util.*;
public class Evaluation
{
public static void main(String[] args)
{
System.out.print("Enter a prefix expression: ");
Scanner scanner = new Scanner(System.in);

// build an expression tree
Node root = buildTree(scanner);

// print prefix expression
System.out.println("prefix expression:");
preorder(root);
System.out.println();

// print postfix expression
System.out.println("postfix expression:");
postorder(root);
System.out.println();

// print infix expression
System.out.println("infix expression:");
inorder(root);
System.out.println();

// evaluate the expression using postfix
System.out.println("Result = " + evaluate(root));
}

// build an expression tree and return the root node of the tree
public static Node buildTree(Scanner sc)
{
// your code here

}

// Postfix expression is the result of a post-order traversal
public static void postorder(Node node)
{
// your code here

}

// Prefix expression is the result of a pre-order traversal
public static void preorder(Node node)
{
// your code here

}

// Infix expression is the result of a in-order traversal
public static void inorder(Node node)
{
// your code here

}

// Evaluate the expression tree using postorder traversal
public static int evaluate(Node node)
{
// your code here

}
}

编辑:这是我必须编写的 Node 类。

 public class Node {
String value;
Node left, right;

Node(String value){
this.value = value;
}

Node(String value, Node left, Node right){
this.left = left;
this.right = right;

}

public boolean isLeaf(){
if()

return true;
}

}

作业的说明是使用给定的方法 buildTree 来构造一棵树,并以前缀表示法计算 4 个给定的表达式:

1.- + 10 * 2 8 3

2./* + 3 14 2 7

3.+ + 4 2 * 3 - 15 1

4./- % + 1 2 3 6 + 2 3

编辑:在之前的作业中,我必须使用堆栈来评估 Postfix 表达式,但是如何使用这棵树来构建和遍历来评估前缀表达式?(我假设操作数和运算符将是节点的值,然后节点将以某种方式链接。)

最佳答案

好吧,让我们考虑一下。是什么使节点成为叶子?

我想说叶子是没有子节点的节点。那么,如何使用以下 boolean 表达式进行 if 检查:if(left == null && right == null)

稍后编辑:事实上,您甚至不需要 if 检查。你可以简单地说,就像

public boolean isLeaf(){
return left == null && right == null;
}

另外,请注意您的重载构造函数

Node(String value, Node left, Node right){
this.left = left;
this.right = right;

}

未正确分配

关于java - 我现在如何使用扫描仪 "build"树? (代码后有说明),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20385704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com