I am trying to build a simple BST that works with strings right now I am just trying to get an insert method to will add tryings. Right now I have it were it will insert int any thoughts on how to change this to take strings
UPDATED:
I have some things working but now I can not get my tree to print out like I want it to?
public class BinaryStringTree {
private String data;
private BinaryStringTree left;
private BinaryStringTree right;
public BinaryStringTree() {
this.data = null;
this.left = null;
this.right = null;
}
public BinaryStringTree(String data) {
this.data = data;
this.left = null;
this.right = null;
}
public void addNode(String data) {
if (this.data == null) {
this.data = data;
} else {
if (this.data.compareTo(data) < 0) {
if (this.left != null) {
this.left.addNode(data);
} else {
this.left = new BinaryStringTree(data);
}
} else {
if (this.right != null) {
this.right.addNode(data);
} else {
this.right = new BinaryStringTree(data);
}
}
}
}
public void traversePreOrder() {
System.out.println(this.data);
if (this.left != null) {
this.left.traversePreOrder();
}
if (this.right != null) {
this.right.traversePreOrder();
}
}
public static void main(String args []){
BinaryStringTree bstree = new BinaryStringTree();
bstree.addNode("Copperfield");
bstree.addNode("Houdini");
bstree.addNode("Cardini");
bstree.addNode("Blackstone");
bstree.addNode("Dante");
bstree.addNode("Malini");
bstree.addNode("Vernon");
bstree.addNode("Liepzig");
bstree.addNode("Wild");
bstree.addNode("Farquar");
bstree.addNode("Thurston");
bstree.addNode("Page");
bstree.addNode("Dedi");
bstree.addNode("Hofzinser");
bstree.addNode("Farmer");
bstree.addNode("Burton");
bstree.addNode("Lorayne");
bstree.addNode("Devant");
bstree.addNode("Maskelyne");
bstree.addNode("Blaney");
bstree.addNode("Ortiz");
bstree.addNode("Munoz");
bstree.addNode("Bertram");
bstree.addNode("Daniels");
bstree.addNode("Beam");
bstree.addNode("Regal");
bstree.addNode("Ammar");
bstree.addNode("Nicola");
bstree.addNode("Fulves");
bstree.addNode("Ganson");
bstree.addNode("Close");
bstree.addNode("Lumiere");
}
}
You can make your BST class generic, which would allow it to take any type for which an ordering is defined.
Instead of using < for comparison, make your class take a type parameter T that implements Comparable<T>, and use key.compareTo(insNode.getKey()) < 0.
If you don't want a generic class, simply replace your int values with Strings, and replace the < operator with compareTo (since String implements Comparable<String>).
Related
hey I am new in the binary trees world and I am trying to compare to values to know which direction should I place the newly added node next.
for now, I tried to do CompareTo method but didn't succeed very much I am now trying to make a private method that will give me the value of the Nodes i would love some help
this is my code now I need to add to the if statement the comparing of nodes so I can proceed :
public void add(E data) {
if(root == null) {
return ;
}
if(root.getLeftSon() == null) {
root.setLeftSon((Node<E>) data);
}
else if(root.getRightSon() == null) {
root.setRightSon((Node<E>) data);
}
}
you have to use generics correctly. Parameter has to extend comparable so you can determinate how to sort it.
class BinaryTree<T extends Comparable<T>> {
Node<T> root;
public Node<T> addRecursive(Node<T> current, T value) {
if (current == null) {
return new Node<T>(value);
}
int ord = value.compareTo(current.value);
if (ord > 0) {
current.left = addRecursive(current.left, value);
} else if (ord < 0) {
current.right = addRecursive(current.right, value);
} else {
// value already exists
return current;
}
return current;
}
static class Node<T extends Comparable<T>> {
T value;
Node<T> left;
Node<T> right;
Node(T value) {
this.value = value;
right = null;
left = null;
}
}
}
I was about to build a binary tree, I didn't use the Generic because the static method can't invoke it so I planned to use the Object class to replace it. In that way, I could enter any type of value like int or String as I want.
But unfortunately, here it is, it is an error.
I put the code below, and pls help with this. I appreciate it.
import java.util.*;
public class MainFunction {
public static void main(String[] args) {
int[] arr = new int[]{1,2,3};
BinaryTree bt = createBTree(arr,0);//this is where the error is ,(The method createBTree(int[], int) is undefined for the type MainFunction)
}
}
public class BinaryTree
{
private Object val;
private BinaryTree leftBTree;
private BinaryTree rightBTree;
public BinaryTree(Object val)
{
this.val = val;
}
private void clearTree()
{
this.val = null;
this.leftBTree = null;
this.rightBTree = null;
}
public void addRightTree (BinaryTree tree)
{
rightBTree = tree;
}
public void addLeftTree (BinaryTree tree)
{
leftBTree = tree;
}
public void editTree(Object val)
{
this.val = val;
}
public boolean isEmpty(BinaryTree tree)
{
if(tree != null)
return false;
return true;
}
public void deleteTree(BinaryTree tree)
{
tree.clearTree();
if(tree.leftBTree != null)deleteTree(tree.leftBTree);
if(tree.rightBTree != null)deleteTree(tree.rightBTree);
}
public static BinaryTree createBTree(Object[] arr,int index)
{
BinaryTree tree = null;
if(index<arr.length&&arr[index] != null)
{
tree = new BinaryTree(arr[index]);
tree.leftBTree = createBTree(arr,index*2+1);
tree.rightBTree = createBTree(arr,index*2+2);
}
return tree;
}
public void preOrderTraversal(BinaryTree tree)
{
System.out.println(tree.val);
if(tree.leftBTree != null)
preOrderTraversal(tree.leftBTree);
if(tree.rightBTree != null)
preOrderTraversal(tree.rightBTree);
}
public void inOrderTraversal(BinaryTree tree)
{
if(tree.leftBTree != null)
inOrderTraversal(tree.leftBTree);
System.out.println(tree.val);
if(tree.rightBTree != null)
inOrderTraversal(tree.rightBTree);
}
public void postOrderTraversal(BinaryTree tree)
{
if(tree.leftBTree != null)
postOrderTraversal(tree.leftBTree);
if(tree.rightBTree != null)
postOrderTraversal(tree.rightBTree);
System.out.println(tree.val);
}
}
First of all, I didn't get why you can't use generics - with static method, you just make method static, too.
Secondly, int[] is NOT Object[] - because primitives in java are not objects, hence your code is not working.
Here's the fixed code with generics that works (note it uses Integer instead of int):
public class BinaryTree<T> {
private T val;
private BinaryTree<T> leftBTree;
private BinaryTree<T> rightBTree;
public BinaryTree(T val) {
this.val = val;
}
private void clearTree() {
this.val = null;
this.leftBTree = null;
this.rightBTree = null;
}
public void addRightTree(BinaryTree<T> tree) {
rightBTree = tree;
}
public void addLeftTree(BinaryTree<T> tree) {
leftBTree = tree;
}
public void editTree(T val) {
this.val = val;
}
public boolean isEmpty(BinaryTree<T> tree) {
return tree == null;
}
public void deleteTree(BinaryTree<T> tree) {
tree.clearTree();
if (tree.leftBTree != null) deleteTree(tree.leftBTree);
if (tree.rightBTree != null) deleteTree(tree.rightBTree);
}
public static <T> BinaryTree<T> createBTree(T[] arr, int index) {
BinaryTree<T> tree = null;
if (index < arr.length && arr[index] != null) {
tree = new BinaryTree<>(arr[index]);
tree.leftBTree = createBTree(arr, index * 2 + 1);
tree.rightBTree = createBTree(arr, index * 2 + 2);
}
return tree;
}
public void preOrderTraversal(BinaryTree<T> tree) {
System.out.println(tree.val);
if (tree.leftBTree != null)
preOrderTraversal(tree.leftBTree);
if (tree.rightBTree != null)
preOrderTraversal(tree.rightBTree);
}
public void inOrderTraversal(BinaryTree<T> tree) {
if (tree.leftBTree != null)
inOrderTraversal(tree.leftBTree);
System.out.println(tree.val);
if (tree.rightBTree != null)
inOrderTraversal(tree.rightBTree);
}
public void postOrderTraversal(BinaryTree<T> tree) {
if (tree.leftBTree != null)
postOrderTraversal(tree.leftBTree);
if (tree.rightBTree != null)
postOrderTraversal(tree.rightBTree);
System.out.println(tree.val);
}
public static void main(String[] args) {
Integer[] arr = new Integer[]{1, 2, 3};
BinaryTree<Integer> bt = createBTree(arr, 0);
}
}
So the idea is to make a Double Ended Priority Queue so far I have got a tree like structure using 2 Linked Lists, I have and interface I have to stick with with no alterations to it. The problem I have got is I have to make 2 methods called getMost and getLeast which gets the most or least node and then makes that node null. But these 2 methods are proving quite difficult to make. How would you go about doing it?
I have tried using recursion but this is proving difficult as I have to select the tree by going tree.root but passing in tree.root into a recursive method always starts it from tree.root
Also I have tried what i have written in inspectLeast() and inspectMost() but Java passes by value not by reference. Any tips?
P.S Not allowed to use anything from java collections or java util.
public class PAS43DPQ implements DPQ
{
//this is the tree
TreeNode tree = new TreeNode();
//this is for the size of the array
int size = 0;
#Override
public Comparable inspectLeast() {
return tree.inspectLeast(tree.root);
}
#Override
public Comparable inspectMost() {
return tree.inspectMost(tree.root);
}
#Override
public void add(Comparable c)
{
tree.add(c);
size++;
}
#Override
public Comparable getLeast() {
if (tree.root != null){
}
return getLeast();
}
#Override
public Comparable getMost(){
Comparable most = getMost();
return most;
}
#Override
public boolean isEmpty() {
return (size > 0)?true:false;
}
#Override
public int size() {
return this.size;
}
class TreeNode{
private Comparable value;
private TreeNode left, right, root;
//constructors
public TreeNode() {}
public TreeNode(TreeNode t) {
this.value = t.value;
this.left = t.left;
this.right = t.right;
this.root = t.root;
}
public TreeNode(Comparable c) {
this.value = (int) c;
}
public void add(Comparable input){
if(root == null){
root = new TreeNode(input);
return;
} else {
insert(root, input);
}
}
public Comparable inspectLeast(TreeNode n){
if (n == null)
return null;
if (n.left == null){
TreeNode least = n;
return least.value;
}
return inspectLeast(n.left);
}
public Comparable inspectMost(TreeNode n){
if (n == null)
return null;
if (n.right == null){
TreeNode most = n;
return most.value;
}
return inspectMost(n.right);
}
public Comparable getMost(TreeNode n){
if(n.right == null)
return n.value;
return tree.getMost(right);
}
public void insert(TreeNode n, Comparable input){
if(input.compareTo(n.value) >= 0){
if (n.right == null) {
n.right = new TreeNode(input);
return;
}
else
insert(n.right, input);
}
if(input.compareTo(n.value) < 0){
if(n.left == null) {
n.left = new TreeNode(input);
return;
}
else
insert(n.left, input);
}
}
}
}
You should be able to modify your TreeNode.getMost(TreeNode n) and TreeNode.getLeast(TreeNode n) similar to the following:
public class TreeNode{
// Also, your parameter here seems to be superfluous.
public TreeNode getMost(TreeNode n) {
if (n.right == null) {
n.root.right = null;
return n;
}
return n.getMost(n);
}
}
Get least should be able to be modified in a similar fashion, but using left rather than right obviously.
I have no idea what direction to take with this - I'm trying to parse an expression "(4 + 3)", and build a Tree from it. However, In my EvalExp method I have no idea what to do from here. The ordering for the expression should be value/operator/value/operator so I've put in 2 stacks, to identify either. Any ideas what I should do next?
public class Tree {
class ExprTreeNode {
ExprTreeNode left, right;
boolean isLeaf;
int value;
char op;
public ExprTreeNode(int value) {
this.value = value;
this.op = op;
this.left = null;
this.right = null;
}
}
private Stack opStk = new Stack();
private Stack valStk = new Stack();
private ExprTreeNode root;
public Tree(String s) {
root = (ExprTreeNode) EvalExp(s);
}
public Object EvalExp(String str) {
Scanner s = null;
try {
s = new Scanner(str);
while (s.hasNext()) {
// push to val stk
if (s.hasNextInt()) {
valStk.push(s.next());
} else {
opStk.push(s.next());
}
}
} finally {
if (s != null) {
s.close();
}
}
//return the root node
return valStk.peek();
}
Why not use a recursive descent parser instead of explicit stacks? Should be something along the lines of
static ExprTreeNode parseExpr(Scanner s) {
ExprTreeNode left = parsePrimary(s);
if (s.hasNext("\\+")) {
s.next("\\+");
ExprTreeNode right = parseExpr(s);
return new ExprTreeNode('+', left, right);
}
return left;
}
public static ExprTreeNode parsePrimary(Scanner s) {
return new ExprTreeNode(parseNextInt());
}
My binary tree looks pretty close to my class materials, but when I print to the console or check for contains(), any adds I'm doing aren't registered.
I don't have a great understanding of static and the debugger is giving me a hint about making a static reference to non-static variable overallRoot, but everything compiles without error or warning in eclipse.
public class BSTSimpleSet<E extends Comparable<E>> implements SimpleSet<E> {
private GTNode<E> overallRoot;
private int size;
public static void main(String[] args) {
BSTSimpleSet<Integer> main = new BSTSimpleSet<Integer>(2);
main.toString();
main.add(3);
main.toString();
main.add(4);
main.toString();
main.add(5);
main.toString();
System.out.print(main.contains(3));
}
public BSTSimpleSet() {
size = 0;
}
public BSTSimpleSet(E input) {
overallRoot = new GTNode<E>(input);
size = 1;
}
public boolean add(E e) {
return add(e, overallRoot);
}
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return false;
} else if (compare < 0) {
return add(e, root.left);
} else {
return add(e, root.right);
}
}
}
public void clear() {
overallRoot = null;
}
public boolean contains(E e) {
return contains(e, overallRoot);
}
private boolean contains(E e, GTNode<E> root) {
if (root == null) {
return false;
} else {
int compare = e.compareTo(root.data);
if (compare == 0) {
return true;
} else if (compare < 0) {
return contains(e, root.left);
} else {
return contains(e, root.right);
}
}
}
public boolean isEmpty() {
if (overallRoot == null) {
return false;
} else {
return true;
}
}
public int size() {
return size;
}
public String toString() {
this.toString(overallRoot, 0);
return null;
}
private void toString(GTNode<E> root, int level) {
if (root != null) {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println(root.data);
toString(root.left, level + 1);
toString(root.right, level + 1);
} else {
for (int i = 0; i < level; i++) {
System.out.print(" ");
}
System.out.println("_");
}
}
private static class GTNode<E extends Comparable<E>> {
public E data;
public GTNode<E> left;
public GTNode<E> right;
public GTNode(E input) {
this(input, null, null);
}
public GTNode(E input, GTNode<E> lNode, GTNode<E> rNode) {
data = input;
left = lNode;
right = rNode;
}
}
}
This code does absolutely nothing.
private boolean add(E e, GTNode<E> root) {
if (root == null) {
root = new GTNode<E>(e);
size++;
return true;
}
...
Java passes in the Object Reference to a method. If you change the Reference, that will not
be propagated back to the calling method. If you change what the Reference refers to
that will be propagated back.
eg
// arrays behave the same way so using them to illustrate.
public void callMethods(){
int[] array = new int[1];
array[0] = 0;
doesNotChange(array);
System.out.println(array[0]);// will print 0
doesAChange(array);
System.out.println(array[0]);// will print 1
}
public void doesNotChange(int[] myArray){
myArray = new int[1];
myArray[0] = 1;
}
public void doesAChange(int[] myArray){
myArray[0] = 1;
}
To avoid these sorts of things I recommend always setting method parameters final.
The GTNode class shouldn't be static. Static classes are classes with only static methods, which means they don't have to be instantiated. The prototypical example of this is the java.lang.Math class: You don't need to call something like Math m = new Math(); m.cos(); to get the cosine, you just call Math.cos(). Since you're creating multiple instances of the GTNode class, make it non-static and you should be good.