2013-11-10 5 views
-1

У меня есть проект, который «Начните с программы tree.java (листинг 8.1) и измените его, чтобы создать двоичное дерево из строки букв (например, A, B и т. Д.)), введенное пользователем. Каждое письмо будет отображаться в его собственном узле. Постройте дерево так, чтобы все узлы , содержащие буквы, были листами. Родительские узлы могут содержать некоторый небуквенный символ , например +. Убедитесь, что каждый родитель У узла есть ровно два ребенка. Не беспокойтесь, если дерево не сбалансировано. Обратите внимание, что это не будет деревом поиска, нет быстрого способа найти данный узел. "Исключение нулевого указателя с использованием двоичных деревьев

import java.io.*; 
import java.util.*; 

class Node 
{ 
    public String iData; // data item (key) 
    public Node leftChild; // this node’s left child 
    public Node rightChild; // this node’s right child 
    public void displayNode() // display ourself 
    { 
     System.out.print('{'); 
     System.out.print(iData); 
     System.out.print("} "); 
    } 
} // end class Node 

class Tree 
{ 
    private Node root; // first node of tree 
    public void setNode(Node newNode) 
    {root = newNode;} 
    public Node getNode() 
    {return root;} 
// ------------------------------------------------------------- 
    public Tree() // constructor 
    { root = null; } // no nodes in tree yet 
// ------------------------------------------------------------- 
public void traverse(int traverseType) 
{ 
    switch(traverseType) 
    { 
     case 1: System.out.print("\nPreorder traversal: "); 
     preOrder(root); 
     break; 
     case 2: System.out.print("\nInorder traversal: "); 
     inOrder(root); 
     break; 
     case 3: System.out.print("\nPostorder traversal: "); 
     postOrder(root); 
     break; 
    } 
    System.out.println(); 
} 
private void preOrder(Node localRoot) 
{ 
    if(localRoot != null) 
    { 
     System.out.print(localRoot.iData + " "); 
     preOrder(localRoot.leftChild); 
     preOrder(localRoot.rightChild); 
    } 
} 
//A function I made to try and get the letters into leaves. 
void preOrderLeaves(Node localRoot, Tree[] forest, int i) 
{ 
    if(localRoot != null) 
    { 
     localRoot.iData = "+"; 
     localRoot.leftChild.iData = "+"; 
     localRoot.rightChild = forest[i].getNode(); 
     preOrderLeaves(localRoot.leftChild, forest, i + 1); 
     preOrderLeaves(localRoot.rightChild, forest, i + 1); 
    } 
} 
// ------------------------------------------------------------- 
private void inOrder(Node localRoot) 
{ 
    if(localRoot != null) 
    { 
     inOrder(localRoot.leftChild); 
     System.out.print(localRoot.iData + " "); 
     inOrder(localRoot.rightChild); 
    } 
} 
// ------------------------------------------------------------- 
private void postOrder(Node localRoot) 
{ 
    if(localRoot != null) 
    { 
     postOrder(localRoot.leftChild); 
     postOrder(localRoot.rightChild); 
     System.out.print(localRoot.iData + " "); 
    } 
} 
// ------------------------------------------------------------- 
public void displayTree() 
{ 
    Stack globalStack = new Stack(); 
    globalStack.push(root); 
    int nBlanks = 32; 
    boolean isRowEmpty = false; 
    System.out.println(
    "......................................................"); 
    while(isRowEmpty==false) 
    { 
     Stack localStack = new Stack(); 
     isRowEmpty = true; 
     for(int j=0; j<nBlanks; j++) 
     System.out.print(' '); 
     while(globalStack.isEmpty()==false) 
     { 
      Node temp = (Node)globalStack.pop(); 
      if(temp != null) 
     { 
       System.out.print(temp.iData); 
       localStack.push(temp.leftChild); 
       localStack.push(temp.rightChild); 
       if(temp.leftChild != null || 
         temp.rightChild != null) 
        isRowEmpty = false; 
     } 
     else 
     { 
      System.out.print("--"); 
      localStack.push(null); 
      localStack.push(null); 
     } 
     for(int j=0; j<nBlanks*2-2; j++) 
      System.out.print(' '); 
     } // end while globalStack not empty 
     System.out.println(); 
     nBlanks /= 2; 
     while(localStack.isEmpty()==false) 
      globalStack.push(localStack.pop()); 
     } // end while isRowEmpty is false 
     System.out.println(
     "......................................................"); 
    } // end displayTree() 
     // ------------------------------------------------------------- 
} 


public class Leaves 
{ 
    //I Tried to create an array of individual trees and then add them to a 
    //larger tree 
public static void main(String[] args) 
{ 
    Tree[] forest = new Tree[10]; 

    Scanner sc = new Scanner(System.in); 

    for(int i = 0; i < 10; i++) 
    { 
     String letter; 
     System.out.println("Enter a letter: "); 
     letter = sc.nextLine(); 

     Node newNode = new Node(); 
     newNode.iData = letter; 
     forest[i].setNode(newNode); //This line causes the null pointer exception 

    } 

    Tree letterTree = new Tree(); 

    letterTree.preOrderLeaves(letterTree.getNode(), forest, 0); 

    letterTree.displayTree(); 
} 

} 

Я получаю исключение Null point, когда пытаюсь установить лес на новый узел. Пожалуйста помоги.

ответ

2
Tree[] forest = new Tree[10]; 

Эта строка создает массив из 10 элементов для деревьев, но не инициализирует ни одно из них. Вы можете к сквозному итерацию через массив и экземпляр каждого элемента, например:

for(int i = 0; i < forest.length; ++i) 
    fores[i] = new Tree(); 

Я также задушевно надеюсь, что все, что код не в том же файле. Попробуйте использовать каждый класс в другом файле.

Смежные вопросы