JAVA: binary trees

泪湿孤枕 提交于 2020-01-02 04:24:05

问题


Here I am trying to practice making binary trees so that I can do different operations with them.

import java.util.*;
import java.lang.*;


public class Main {

public static void main(String[] args) {

}
}

//Building Binary Trees
class bTree {

static class Node { //remember to initilize a root

    String value;
    Node left, right;

    Node(String value, Node left, Node right) {
        this.value = value;
        this.left = left;
        this.right = right;
    }
    Node(String value) //THIS IS A SIBLING CONSTRUCTOR
    {
        this(value, null, null);
    }

    Node root = new Node("ROOT");
    Node lefty = new Node("LEFT0");
    Node righty = new Node("RIGHT0");
    root.left = lefty;
    root.right = righty;
}
Node root = null;
}

Why am I getting the error: Identifier expected at the root.left and root.right assignment?

Thanks!


回答1:


The assignment statements

root.left = lefty;
root.right = righty;

are not allowed on the class level. You can achieve the effect you want changing this line

Node root = new Node("ROOT");

to this

Node root = new Node("ROOT", lefty, righty);

which takes advantage of your three-argument constructor.

However, you may want to reconsider the placement of root, lefty and righty. They are probably intended in the bTree class. Also, there is a convention that encourages naming class capitalizing the first letter of each word, e.g. BinaryTree.



来源:https://stackoverflow.com/questions/9648756/java-binary-trees

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!