简体   繁体   English

访问树java中的各个节点

[英]Accessing individual nodes in a tree java

I am making a class ExpTree which includes a method to generate pre order output and return this as a string. 我正在创建一个ExpTree类,它包含一个生成预订输出并将其作为字符串返回的方法。 So far I have the basic code to make the tree but I am not sure how to write to pre order method. 到目前为止,我有基本的代码来制作树,但我不知道如何写入预订方法。

I have tried to access the tree data by making an ExpTree object in the main method, and then in my preorder method writing 'x.root' in a print statement. 我试图通过在main方法中创建一个ExpTree对象来访问树数据,然后在我的预订方法中在print语句中编写'x.root'。 This however would return 'ExpTree.OperatorNode@7637f22'. 然而,这将返回'ExpTree.OperatorNode@7637f22'。 When ideally I was hoping that it would return some of the values that are in the tree. 理想情况下,我希望它会返回树中的一些值。

I am a beginner to trees in java so if someone could perhaps explain what I need to do here that would be great! 我是java中的树的初学者,所以如果有人可以解释我在这里需要做什么就会很棒!

Thanks 谢谢

EDIT - If it isnt clear, what I am asking is that I want to be able to order the Exp trees that are supplied to the method 'preorder' using the preorder traversal. 编辑 - 如果不清楚,我要问的是我希望能够使用preorder遍历来命令提供给方法'preorder'的Exp树。 The output of this method should be as a string. 此方法的输出应为字符串。

The problem is that I dont know how to access the potential parts of the ExpTree so I am unable to order them. 问题是我不知道如何访问ExpTree的潜在部分,所以我无法订购它们。

You do not need char expression in your leafNode. 您的leafNode中不需要char expression leafNode can be just integers and the OperatorNode has the leafNodes (integers) and expression char. leafNode可以只是整数,OperatorNode有叶子节点(整数)和表达式char。

public static void main(String[] args)
{

    ExpTree tree = new ExpTree('*', 1 , 2);
    System.out.println(tree.preOrder());

}

//Class Exp Tree creates Expression Tree with method to generate pre order output.

package ExpTree;


public class ExpTree {

    public Node root;

    public ExpTree ( char x, int y, int z){

        this.root = new OperatorNode(x, y, z);
    }

    public String preOrder (){

        return root.preOrder();
    }

}

abstract class Node {
    public abstract String preOrder();
}

class OperatorNode extends Node {

    char operator;
    Node left;
    Node right;

    public OperatorNode(char x, int y, int z){

        this.operator = x;
        this.left = new leafNode (y);
        this.right = new leafNode (z);
    }

    public String preOrder() {
        return this.operator + this.left.preOrder() + this.right.preOrder();
    }

}

class leafNode extends Node{
    int value;

    public leafNode(int x){
         this.value = x;
    }

    public String preOrder() {
        return Integer.toString(this.value);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM