By the function height(Node) I have the height of each node in my tree.for my each Node in tree, i want to determine subtraction of height of left Node from Right Node.
I just should iterate through the tree. but I have StackOverflow error in my code.
give me some help. I think there is something wrong in other part of my program.
public class AvlTree {
private Node root = new Node (0,0,"","");
void devision( Node tmp){
tmp=root;
if(tmp.getLeftChild()!=null){
tmp.devisionNumber=height(tmp.getLeftChild())-height(tmp.getRightChild());
devision(tmp.getLeftChild());
}
if(tmp.getRightChild()!=null){
tmp.devisionNumber=height(tmp.getLeftChild())-height(tmp.getRightChild());
devision(tmp.getRightChild());
}
}
int height(Node node){
if(node==null)
return -1;
int left=height(node.getLeftChild());
int right=height(node.getRightChild());
if(left>right)
{
return left+1;
}
else
return right +1;
}
void insert (Node newNode ){
Node tmp=root;
if(root.getStdNum()==0){
root=newNode;
root.setLeftChild(null);
root.setRightChild(null);
root.setRoot(null);
}
else{
while(true) {
if(newNode.getStdNum()<tmp.getStdNum()){
if(tmp.getLeftChild()==null)
break;
else
tmp=tmp.getLeftChild();
}
if(newNode.getStdNum()>tmp.getStdNum()){
if(tmp.getRightChild()==null)
break;
else
tmp=tmp.getRightChild();
}
}
////////////////////////
if(newNode.getStdNum()<tmp.getStdNum())
{
tmp.setLeftChild(newNode);
newNode.setRoot(tmp);
}
if(newNode.getStdNum()>tmp.getStdNum())
{
tmp.setRightChild(newNode);
newNode.setRoot(tmp);
}
}
}
}
public class Node {
private int StdNum;
private int Avarage;
private String Name;
private String FamillyName;
private Node Root;
public int devisionNumber;
private Node LeftChild;
private Node RightChild;
public Node(int stdNum,int Avarage,String Name,String FamillyName){
this.StdNum=stdNum;
this.Avarage=Avarage;
this.Name=Name;
this.FamillyName=FamillyName;
}
public boolean CheckForNull (Object a){
boolean check;
if(a==null){
check=true;
}
else
check=false;
return check;
}
public void ShowData(){
System.out.println("ID: "+ getStdNum());
System.out.println("Avg: " + getAvarage());
System.out.println("Name: "+ getName());
System.out.println("Familly: "+ getFamillyName()+"\n");
if(CheckForNull(this.getLeftChild())==false)
System.out.println("leftNode ID: "+ getLeftChild().getStdNum() );
else System.out.println("LeftChild : Null ");
if(CheckForNull(this.getRightChild())==false)
System.out.println("RightNode ID: "+ getRightChild().getStdNum());
else System.out.println("RightChild : Null ");
if(CheckForNull(this.getRoot())==false)
System.out.println("Root ID: "+ getRoot().getStdNum());
else System.out.println("Root : Null ");
}
public int getStdNum() {
return StdNum;
}
public void setStdNum(int stdNum) {
StdNum = stdNum;
}
public int getAvarage() {
return Avarage;
}
public void setAvarage(int avarage) {
Avarage = avarage;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getFamillyName() {
return FamillyName;
}
public void setFamillyName(String famillyName) {
FamillyName = famillyName;
}
public Node getRoot() {
return Root;
}
public void setRoot(Node root) {
Root = root;
}
public Node getLeftChild() {
return LeftChild;
}
public void setLeftChild(Node leftChild) {
LeftChild = leftChild;
}
public Node getRightChild() {
return RightChild;
}
public void setRightChild(Node rightChild) {
RightChild = rightChild;
}
}
you always set the node to root (line 2 of the method), so your recursion does not go down the subtrees, but restarts every time ... so the recursion never ends - resulting in a stack overflow.
Related
This is a homework assignment i'm working on and I'm having a little trouble with it. I've implemented my own version of a binary search tree rather than using JDK. I'm inserting multiple student objects into the binary search tree in terms of the student's ID, which is a type string. I'm not getting any compile errors but the program keeps returning that the value is not found when it should be the fourth student that was inserted into the tree. I've implemented all of the find methods already, but not sure where I'm going wrong with them, since the output should be saying that the value was found.
Output:
run:
11114 not found
BUILD SUCCESSFUL (total time: 0 seconds)
Homework5.class / main:
package homework5;
import java.util.LinkedList;
public class Homework5 {
static Roster rost = new Roster();
public static void main(String[] args) {
addStudent();
lookupStudent("11114");
}
// add students to the roster
static void addStudent() {
rost.addStudent(new Student("11111", "Jon", "Benson"));
rost.addStudent(new Student("11112", "Erick", "Hooper"));
rost.addStudent(new Student("11113", "Sam", "Shultz"));
rost.addStudent(new Student("11114", "Trent", "Black"));
rost.addStudent(new Student("11115", "Michell", "Waters"));
rost.addStudent(new Student("11116", "Kevin", "Johnson"));
}
// lookup a student in the roster
static void lookupStudent(String id) {
if (rost.find(id) != null) {
System.out.println(id + " found");
} else {
System.out.println(id + " not found");
}
}
}
Student.class
class Student implements Comparable<Student> {
String id;
String firstName;
String lastName;
Student(String id, String fName, String lName) {
this.id = id;
this.firstName = fName;
this.lastName = lName;
}
public String getName() {
return lastName;
}
public void setName(String lName) {
this.lastName = lName;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public int compareTo(Student other) {
return this.getId().compareTo(other.getId());
}
public void addCourse(String id) {
LinkedList list = new LinkedList();
list.add(id);
}
}
Roster.class
class Roster {
Student root;
int numStudents;
BST<Student> roster = new BST<>();
public Roster() {
root = null;
numStudents = 0;
}
public void addStudent(Student st) {
roster.insert(st);
numStudents++;
}
public Student find(String id) {
roster.find(id);
return null;
}
BST.java
package homework5;
class BST<Roster extends Comparable> {
private Node root;
public BST() {
root = null;
}
// Generic find method
public Node find(String id) {
Node current = root;
while (id.compareTo(current.element.getId()) != 0) {
if (id.compareTo(current.element.getId()) < 0) {
current = current.left;
}
else {
current = current.right;
}
if (current == null) {
return null;
}
}
return current;
}
public void insert(Student st) {
Node newNode = new Node(st);
if (root == null) {
root = newNode;
} else {
Node current = root;
Node parent = null;
while (true) {
parent = current;
if (st.compareTo(current.element) < 0) {
current = current.left;
if (current == null) {
parent.left = newNode;
return;
}
} else {
current = current.right;
if (current == null) {
parent.right = newNode;
return;
}
}
}
}
}
// Recursive method - traverse generic BST
// While root is not equal to null visit left node and print value
// of root, then visit right node. Repeat until root becomes null
private void inOrder(Node localRoot) {
if (localRoot != null) {
inOrder(localRoot.left);
System.out.print(localRoot.element + " ");
inOrder(localRoot.right);
}
}
}
class Node {
protected Student element;
protected Node left;
protected Node right;
public Node(Student st) {
element = st;
}
}
Roster.find() always returns null.
Change it to
public Student find(String id) {
return roster.find(id).element;
}
your code looks fine... a few misconceptions like the comments suggested, just change those couple of lines
public Student find(String id) {
return roster.find(id);
}
and return current.element from roster.find() change the signature to public Student find(String id)
Note: keep in mind this will effect the generic property of the code, a better approach is to implement node as a generic data container e.g Node<Student> make roster.find() return a Node object and get the data from the node so you can return Student object at the end
or at least change only this function instead (it's a better solution than mine)
public Student find(String id) {
return roster.find(id).element;
}
Node
private Object data;
private Node link;
private Node next;
private Node prev;
public Object getData() {
return data;
}
public void setData(Object data) {
this.data = data;
}
public Node getLink() {
return link;
}
public void setLink(Node link) {
this.link = link;
}
public Node(Object data) {
this.data = data;
this.link = null;
}
public Node getNextNode() {
return next;
}
public Node getPrevNode() {
return prev;
}
public void setNextNode(Node n) {
next = n;
}
public void setPrevNode(Node n) {
prev = n;
}
Item
private int id;
private String name;
private String type;
private double price;
public Item(int id, String name, String type, double price) {
this.id = id;
this.name = name;
this.type = type;
this.price = price;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public String getType() {
return type;
}
public double getPrice() {
return price;
}
public void setId(int id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setType(String type) {
this.type = type;
}
public void setPrice(double price) {
this.price = price;
}
#Override
public String toString() {
return "Item: " + "ID: " + id + ", Name: " + name + ", Type: " + type + ", Price: " + price;
}
LinkedList
private Node head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void addFront(int n) {
Node newNode = new Node(n);
newNode.setLink(head);
head = newNode;
count++;
}
public void deleteFront() {
if (count > 0) {
head = head.getLink();
count--;
}
}
public void AddItemToFront(Item p) {
Node newNode = new Node(p);
newNode.setLink(head);
head = newNode;
count++;
}
public void DisplayItems() {
Node temp = head;
while(temp != null) {
System.out.println(temp.getData());
temp = temp.getLink();
}
}
public void RemoveItemAtPosition(int n) {
if(n == 1) {
Node x = head;
head = x.getLink();
count--;
}
else if (n > count || n < 0) {
System.out.println("The index you entered is out of bound.");
}
else {
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Node temp = x;
x = temp.getPrevNode();
x.setNextNode(temp.getNextNode());
temp = null;
count--;
}
}
I'm trying to remove a Node at a position given integer n.
I tried researching on SO before posting here and the above is the code that i came out with. However, the code returned me an error saying >java.lang.NullPointerException at LinkedList.java:74 at main:35
The Node is actually an object that is being added to the LinkedList
I checked your code I see that you have some bugs.
your mistakes are:
1 -you use linked object.
2- try to access previous and next without initialization.
3- you only care on the next node.
I removed link form Node class and I do some changes into LinkedList:
public class LinkedList {
private Node head; // first node in the linked list
private int count;
public int getCount() {
return count;
}
public Node getHead() {
return head;
}
public LinkedList() {
head = null; // creates an empty linked list
count = 0;
}
public void addFront(int n) {
Node newNode = new Node(n);
if (head == null) {
head = newNode;
} else {
Node node = head;
head = newNode;
head.setNextNode(node);
node.setPrevNode(head);
}
count++;
}
public void deleteFront() {
if (count > 0) {
head = head.getNextNode();
head.setPrevNode(null);
count--;
}
}
public void AddItemToFront(Item p) {
Node newNode = new Node(p);
if (head == null) {
head = newNode;
} else {
Node node = head;
head = newNode;
head.setNextNode(node);
node.setPrevNode(head);
}
count++;
}
public void DisplayItems() {
Node temp = head;
while (temp != null) {
System.out.println(temp.getData());
temp = temp.getNextNode();
}
}
public void RemoveItemAtPosition(int n) {
if (n == 1) {
deleteFront();
} else if (n > count || n < 0) {
System.out.println("The index you entered is out of bound.");
} else {
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Node temp = x;
temp.getPrevNode().setNextNode(temp.getNextNode());
temp.getNextNode().setPrevNode(temp.getPrevNode());
temp = null;
count--;
}
}
}
When checking the provided source code, in the function AddItemToFront(Item p) only the linked-list is managed with newNode.setLink(head);. Both Node next; and Node prev; are never initialized and never used before in the function removeItemAtPosition(int n).
Warning: your Linked-List is managed on reverse (due to the function void AddItemToFront(Item p)).
A simple way to solve your problem should to use only Node link; also in the function removeItemAtPosition(int n).
Step 1 - in RemoveItemAtPosition(int n), modify the search of the nth Node in the for-loop
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getLink(); // Use Node link
}
Instead of
Node x = head;
for (int i = 1; i < n; i++) {
x = x.getNextNode();
}
Step 2 - in RemoveItemAtPosition(int n), connect the next node link to the node before
Node temp = x.getLink();
x.setLink(temp.getLink());
count--;
Instead of
Node temp = x;
x = temp.getPrevNode();
x.setNextNode(temp.getNextNode());
temp = null;
count--;
So I'm fairly new to Java and programming and I was wondering how to create a node class?
So far I have:
public class ItemInfoNode{
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev){
info = info;
next = next;
prev = prev;
}
public void setInfo(ItemInfo info){
info = info;
}
public void setNext(ItemInfoNode node){
next = node;
}
public void setPrev(ItemInfoNode node){
prev = node;
}
public ItemInfo getInfo(){
return info;
}
public ItemInfoNode getNext(){
return next;
}
public ItemInfoNode getPrev(){
return prev;
}
}
Pretty much the question asked for those methods so I put those down but, the next question asks me to refer to the head and tail of ItemInfoNode nodes. Just a bit confused here. Thanks
EDIT: Thanks for the help guys! I'm trying to create an "InsertInfo" method that puts information like the name, price, tag number, etc. Into one node. How do I go about creating this method?
So far I got this.. I have an Iteminfo constructor in a different class that has all of these but, I'm not sure how to use that/if I am even supposed to do..
public void InsertInfo(String name, String rfdnumber, double price, String original_position){
head = new ItemInfoNode (Iteminfo, head);
}
Welcome to Java!
This Nodes are like a blocks, they must be assembled to do amazing things!
In this particular case, your nodes can represent a list, a linked list, You can see an example here:
public class ItemLinkedList {
private ItemInfoNode head;
private ItemInfoNode tail;
private int size = 0;
public int getSize() {
return size;
}
public void addBack(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, null, tail);
this.tail.next =node;
this.tail = node;
}
}
public void addFront(ItemInfo info) {
size++;
if (head == null) {
head = new ItemInfoNode(info, null, null);
tail = head;
} else {
ItemInfoNode node = new ItemInfoNode(info, head, null);
this.head.prev = node;
this.head = node;
}
}
public ItemInfo removeBack() {
ItemInfo result = null;
if (head != null) {
size--;
result = tail.info;
if (tail.prev != null) {
tail.prev.next = null;
tail = tail.prev;
} else {
head = null;
tail = null;
}
}
return result;
}
public ItemInfo removeFront() {
ItemInfo result = null;
if (head != null) {
size--;
result = head.info;
if (head.next != null) {
head.next.prev = null;
head = head.next;
} else {
head = null;
tail = null;
}
}
return result;
}
public class ItemInfoNode {
private ItemInfoNode next;
private ItemInfoNode prev;
private ItemInfo info;
public ItemInfoNode(ItemInfo info, ItemInfoNode next, ItemInfoNode prev) {
this.info = info;
this.next = next;
this.prev = prev;
}
public void setInfo(ItemInfo info) {
this.info = info;
}
public void setNext(ItemInfoNode node) {
next = node;
}
public void setPrev(ItemInfoNode node) {
prev = node;
}
public ItemInfo getInfo() {
return info;
}
public ItemInfoNode getNext() {
return next;
}
public ItemInfoNode getPrev() {
return prev;
}
}
}
EDIT:
Declare ItemInfo as this:
public class ItemInfo {
private String name;
private String rfdNumber;
private double price;
private String originalPosition;
public ItemInfo(){
}
public ItemInfo(String name, String rfdNumber, double price, String originalPosition) {
this.name = name;
this.rfdNumber = rfdNumber;
this.price = price;
this.originalPosition = originalPosition;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRfdNumber() {
return rfdNumber;
}
public void setRfdNumber(String rfdNumber) {
this.rfdNumber = rfdNumber;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public String getOriginalPosition() {
return originalPosition;
}
public void setOriginalPosition(String originalPosition) {
this.originalPosition = originalPosition;
}
}
Then, You can use your nodes inside the linked list like this:
public static void main(String[] args) {
ItemLinkedList list = new ItemLinkedList();
for (int i = 1; i <= 10; i++) {
list.addBack(new ItemInfo("name-"+i, "rfd"+i, i, String.valueOf(i)));
}
while (list.size() > 0){
System.out.println(list.removeFront().getName());
}
}
I would like to create and print a tree from string which read from file. I tried the following code but I could not print the tree in a correct way.
I have file file.txt which has for example the following string
com-bo-news-2012,12
com-bo-news-2015,3
net-php-www,20
net-phototrails,3
I would like to create a tree like
root
|
com(17) //calculated as (2+12+3)
|bo(17)
|news(17)
|2012 (12)
|2015(3)
|net(23)
|php(20)
|www(20)
|phototrails(3)
I tried the following code
public void ReadFile(String inputFile){
Map<String[],Integer> map = new HashMap<String[], Integer>();
BufferedReader br=null;
String file1 = "";
try {
br = new BufferedReader(new FileReader(inputFile));
while ((file1 = br.readLine()) != null) {
String path[]=file1.split(",");
String nodes[]=path[0].split("-");
map.put(nodes,Integer.parseInt(path[1].trim()));
}
buildTree(map);
br.close();
}catch(Exception e){
System.out.println(e);
}
}
public void buildTree(Map<String[],Integer> map)
{
Map<String, Node> wordMap = new HashMap<String, Node>();
Node root = new Node();
for (Map.Entry<String[], Integer> entry : map.entrySet()) {
String key[] = entry.getKey();
Integer value = entry.getValue();
Node current=root;
Node p;
for(String node:key)
{
if(wordMap.containsKey(node)){
p = wordMap.get(node);
p.addCost(value);
} else {
p=new Node(node,value);
wordMap.put(node, p);
System.out.println("AddNode: "+p.getName());
}
current.addChild(p);
current = p;
}
}
printTree(root);
}
public void printTree(Node doc) { ///print tree
if (doc == null) {
System.out.println("Nothing to print!!");
return;
}
try {
System.out.println(doc.getName() + " " + doc.getCount());
List<Node> cl = doc.getChildren();
for (int i = 0; i < cl.size(); i++) {
Node node = cl.get(i);
System.out.println(
"\t" + node.getName() + " ->" + node.getCount());
}
List<Node> nl = doc.getChildren();
for (int i = 0; i < nl.size(); i++) {
Node node = nl.get(i);
printTree(node);
}
} catch (Throwable e) {
System.out.println("Cannot print!! " + e.getMessage());
}
}
public class Node {
private String name;
private int count;
private List<Node> children;
public Node() {
this(null, 0);
}
public Node(String name, int count) {
this.name = name;
this.count = count;
this.children = new ArrayList<Node>();
}
public Node(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public List<Node> getChildren() {
return children;
}
public void setChildren(List<Node> children) {
this.children = children;
}
public void addChild(Node n) {
for (Node nn : children) {
if (nn.name.equals(n.name)) {
return;
}
}
this.children.add(n);
}
public void addCost(int i) {
this.count += i;
}
}
But I could not print the tree in a correct way which mentioned. It sometimes make a infinite loop when it will get same node as a child. Could anyone please guide me for that? Thanks.
I have added the code to generate the Tree kind of structure, have used the composite pattern.
package com.test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class TestMain {
public static void main(String[] args) {
TestMain testMain = new TestMain();
List<String> testData = new ArrayList<String>();
testData.add("com-bo-news-2012,12");
testData.add("com-bo-news-2015,3");
testData.add("net-php-www,20");
testData.add("net-phototrails,3");
MyNode myNode = new MyNode("ROOT");
for (String string : testData) {
List<String> l = new ArrayList<String>();
l.addAll(Arrays.asList(string.split("-")));
testMain.buildTree(l, myNode);
}
printTree(myNode, 1);
}
private void buildTree(List<String> nodeNames, MyNode node) {
if (nodeNames.isEmpty()) {
return;
}
String nodeName = nodeNames.remove(0);
MyNode myNode = new MyNode(nodeName);
int index = node.getNodes().indexOf(myNode);
if (index == -1) {
node.getNodes().add(myNode);
} else {
myNode = node.getNodes().get(index);
}
buildTree(nodeNames, myNode);
}
private static void printTree(MyNode myNode, int tabCount) {
for (int i = 0; i < tabCount; i++) {
System.out.print("\t");
}
System.out.print(myNode.getNode() + "\n");
for (int i = 0; i < tabCount; i++) {
System.out.print("\t");
}
System.out.println("|");
for (MyNode node : myNode.getNodes()) {
printTree(node, ++tabCount);
}
}
}
package com.test;
import java.util.ArrayList;
import java.util.List;
public class MyNode {
private String node;
private List<MyNode> nodes;
public MyNode(String node) {
super();
this.node = node;
this.nodes = new ArrayList<MyNode>();
}
public MyNode(String node, List<MyNode> nodes) {
super();
this.node = node;
this.nodes = nodes;
}
public String getNode() {
return node;
}
public void setNode(String node) {
this.node = node;
}
public List<MyNode> getNodes() {
return nodes;
}
public void setNodes(List<MyNode> nodes) {
this.nodes = nodes;
}
#Override
public int hashCode() {
return node.hashCode();
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass().equals(obj.getClass())) {
return ((MyNode) obj).getNode().equals(node);
}
return false;
}
#Override
public String toString() {
return node + "[" + nodes.size()+"]";
}
}
Output needs to be formatted a bit, let me know if you have any questions
This question already exists:
Write an address book in java using a binary search tree [closed]
Closed 9 years ago.
Hello I am writing an AddressBook application in java and I have written the whole program. The only thing is that its not working as expected and there are no errors in the code so i am unable to troubleshoot it. Any help would be much appriciated.
EDIT: This is not a duplicate question as this includes all the methods. The other one didn't have the main method and is incomplete and as it was closed i was forced to ask a new question. Makes sense?
package com.addressbook;
public abstract class KeyedItem<KT extends Comparable<? super KT>> {
private KT searchKey;
public KeyedItem(KT key){
searchKey = key;
}
public KT getKey(){
return searchKey;
}
}
package com.addressbook;
public class People extends KeyedItem<String> {
private String address;
private String phone;
public People(String n, String a, String p){
super(n);
this.address = a;
this.phone = p;
}
public void setAddress(String a){
address = a;
}
public void setPhone(String p){
phone = p;
}
public String toString(){
return "Name:" + getKey() + "\nAddress:" + address + "\nPhone:" + phone;
}
public String getTheKey(){
return getKey();
}
}
package com.addressbook;
public class BinaryNode{
// Friendly data; accessible by other package routines
private People people; // The data in the node
private BinaryNode left; // Left child
private BinaryNode right; // Right child
// Constructors
public BinaryNode(People pe, BinaryNode l, BinaryNode r) {
people = pe;
left = l;
right = r;
}
public BinaryNode(People pe) {
people = pe;
left = right = null;
}
public void setData(People p){
people = p;
}
public String getSearch(){
return people.getTheKey();
}
public People getData(){
return people;
}
public BinaryNode getLeft(){
return left;
}
public BinaryNode getRight(){
return right;
}
}
package com.addressbook;
import com.addressbook.People;
import com.addressbook.BinaryNode;
public class AddressBook {
private BinaryNode root;
public AddressBook() {
super();
}
public AddressBook(People p) {
super();
root = new BinaryNode(p);
}
public void insert(People p){
insert(p, root);
}
public People get(String key) {
BinaryNode node = root;
while (node != null) {
if (key.compareTo(node.getSearch()) == 0) {
return node.getData();
}
if (key.compareTo(node.getSearch()) < 0) {
node = node.getLeft();
} else {
node = node.getRight();
}
}
return null;
}
protected BinaryNode insert(People p, BinaryNode node) {
if (node == null) {
return new BinaryNode(p);
}
if (p.getTheKey().compareTo(node.getSearch()) == 0) {
return new BinaryNode(p, node.getLeft(), node.getRight());
} else {
if (p.getTheKey().compareTo(node.getSearch()) < 0) { // add to left subtree
insert(p, node.getLeft());
} else { // add to right subtree
insert(p, node.getRight());
}
}
return node;
}
public void remove(String key) {
remove(key, root);
}
protected BinaryNode remove(String k, BinaryNode node) {
if (node == null) { // key not in tree
return null;
}
if (k.compareTo(node.getSearch()) == 0) { // remove this node
if (node.getLeft() == null) { // replace this node with right child
return node.getRight();
} else if (node.getRight() == null) { // replace with left child
return node.getLeft();
} else {
// replace the value in this node with the value in the
// rightmost node of the left subtree
node = getRightmost(node.getLeft());
// now remove the rightmost node in the left subtree,
// by calling "remove" recursively
remove(node.getSearch(), node.getLeft());
// return node; -- done below
}
} else { // remove from left or right subtree
if (k.compareTo(node.getSearch()) < 0) {
// remove from left subtree
remove(k, node.getLeft());
} else { // remove from right subtree
remove(k, node.getRight());
}
}
return node;
}
protected BinaryNode getRightmost(BinaryNode node) {
assert(node != null);
BinaryNode right = node.getRight();
if (right == null) {
return node;
} else {
return getRightmost(right);
}
}
protected String toString(BinaryNode node) {
if (node == null) {
return "";
}
return node.getData().toString() + "(" + toString(node.getLeft()) + ", " +
toString(node.getRight()) + ")";
}
public static void main(String[] arguments) {
AddressBook tree = new AddressBook();
People p1 = new People("person 1", "adresa 1", "404040404");
People p2 = new People("person 2", "adresa 2", "4040434345");
People p3 = new People("person 3", "adresa 3", "346363463");
People p4 = new People("person 4", "adresa 4", "435346346");
People p5 = new People("person 5", "adresa 5", "4363907402");
tree.insert(p1);
tree.insert(p2);
tree.insert(p3);
tree.insert(p4);
tree.insert(p5);
System.out.println(tree.get("person 1"));
}
}
On one hand:
public void insert(People p){
insert(p, root);
}
but that method begins with
protected BinaryNode insert(People p, BinaryNode node) {
if (node == null) {
return new BinaryNode(p);
}
which means, considering both pieces together, you always ignore the new root and hence your tree never fills. Try this instead:
public void insert(People p){
root = insert(p, root);
}
In the same manner you ignore the return value of insert inside insert too. You should handle them in a similar manner.