我们在我的数据结构类中有一个任务,我们必须手动构建一个总共有 7 个节点的二叉树,并在前序遍历中显示每个节点中的数据。根节点有 2 个孩子,这 2 个孩子中的每一个都有 2 个孩子。我已经到了创建整个左侧到第一棵树的末尾的地步,但是一旦我创建了第一个右孩子,我就陷入了空指针异常。我已经搜索了与此类似的其他项目,但我似乎仍然无法找出这段代码的问题所在。我发现创建树的代码比我们分配的要好得多,但是我们在课堂上仅限于手动创建左右子节点。任何外部观点来帮助可能创建一个简单的程序将不胜感激!
public class Main {
public static void main(String[] args) {
Node a = new Node(1);
Node b = new Node(2);
Node c = new Node(3);
Node d = new Node(4);
Node e = new Node(5);
Node f = new Node(6);
Node g = new Node(7);
BinaryTree t = new BinaryTree(a);
t.addleft(a);
t.addleft(b);
t.addleft(c);
t.addParent();
t.addRight(d);
t.addParent();
//t.addParent();
//t.addRight(e);
//t.addleft(f);
//t.addParent();
//t.addRight(g);
//System.out.println(n.getData());
t.preOrder(t.root);
}
}
public class BinaryTree {
Node root;
Node current;
public BinaryTree(Node n){
root = n;
n.setParent(current);
current = n;
}
public void addleft(Node n){
current.setLeft(n);
current = n;
}
public void addRight(Node n){
current.setRight(n);
current = n;
}
public void addParent(){
current = current.getParent();
}
public void preOrder(Node n){
if(n != null){
System.out.println(n.getData());
preOrder(n.leftChild);
preOrder(n.rightChild);
return;
}
return;
}
}
public class Node {
Node parent;
Node rightChild;
Node leftChild;
int data;
public Node(int i) {
data = i;
parent = null;
rightChild = null;
leftChild = null;
}
public int getData() {
return data;
}
public Node getParent() {
return parent;
}
public void setParent(Node aParent) {
parent = aParent;
}
public Node getLeft() {
return leftChild;
}
public void setLeft(Node left) {
leftChild = left;
}
public void setRight(Node right) {
rightChild = right;
}
public Node getRight() {
return rightChild;
}
}