Search

Java - Data Structures - non linear - Binary Tree from the scratch

 

package datastructures.linear;

public class TreeFromTheScratch {
public static void main(String[] args) {
TreeImpl tree = new TreeImpl();
tree.insert(10);
tree.insert(5);
tree.insert(15);
tree.insert(6);
tree.insert(1);
tree.insert(8);
tree.insert(12);

System.out.println(("6 "+(tree.find(6)?"Found":"Not Found")));
System.out.println(("7 "+(tree.find(7)?"Found":"Not Found")));
}
}

class TreeImpl{
private Node root;

public void insert(int value){
var newNode = new Node(value);
if(null==root){
root = newNode;
return;
}
var current= root;
while(true){
if(current.value>value){
if(current.leftChild==null){
current.leftChild = newNode;
break;
}
current = current.leftChild;
} else {
if(current.rightChild==null){
current.rightChild = newNode;
break;
}
current = current.rightChild;
}
}
}

public boolean find(int value){
var current = root;
while (current!=null){
if(current.value==value){
return true;
} else if(current.value>value){
current = current.leftChild;
} else {
current = current.rightChild;
}
}
return false;
}

private class Node{
private int value;
private Node leftChild;
private Node rightChild;

public Node(int value) {
this.value = value;
}

@Override
public String toString() {
return "Node{" +
"value=" + value +
", leftChild=" + ((null!=leftChild)?leftChild.value:"null") +
", rightChild=" + ((null!=rightChild)?rightChild.value:"null") +
'}';
}
}
}

 

No comments:

Post a Comment

Java Interfaces vs. Abstract class

Summary of the similarities and differences between the Interfaces and Abstract class Abstract class Interface Has a constructor Yes No An i...