How to implement keySet method in Binary Search Tree - java

import tree.BinaryTree;
public class TreeMap<K extends Comparable<K>, V> implements MyMap<K, V> {
private BinaryTree<Element> map;
java.util.Set<K> keys;
private int size;
#Override
public java.util.Set<K> keySet() {
inorder(map);
return keys;
}
public String toString() {
return map.toString();
}
private class Element {
K key;
V value;
public Element(K key, V value) {
this.key = key;
this.value = value;
}
public int compareTo(Element that) {
return this.key.compareTo(that.key);
}
public String toString() {
return (key.toString());
}
}
private void inorder(BinaryTree<Element> tree) {
if (tree != null) {
inorder(tree.getLeft());
keys.add(tree.getRoot().key);
inorder(tree.getRight());
}
}
}
Hey guys! :)
I'm having a lot of trouble with adding keys in inorder to my set of keys.
How do I append keys to the set? :/
The worst part is that it isn't showing me the exception all it says is
at TreeMap.inorder(TreeMap.java:188)
at TreeMap.keySet(MyTreeMap.java:60)
at TreeMap.main(MyTreeMap.java:244)
Java Result: 1
This is just a snippet of my code, everything works but my keySet/inorder methods. Line 188 on my code is
keys.add(tree.getRoot().key);
I have searched, retried, and searched again but cant get anywhere. I would appreciate any help you guys can give me.
Thanks in advance! :)
Here is the BinaryTree class
public class BinaryTree<E>
{
private E root;
private BinaryTree<E> left;
private BinaryTree<E> right;
public BinaryTree(E paramE, BinaryTree<E> paramBinaryTree1, BinaryTree<E> paramBinaryTree2)
{
this.root = paramE;
this.left = paramBinaryTree1;
this.right = paramBinaryTree2;
}
public BinaryTree(E paramE)
{
this(paramE, null, null);
}
public E getRoot()
{
return (E)this.root;
}
public BinaryTree<E> getLeft()
{
return this.left;
}
public BinaryTree<E> getRight()
{
return this.right;
}
public E setRoot(E paramE)
{
Object localObject = this.root;
this.root = paramE;
return (E)localObject;
}
public BinaryTree<E> setLeft(BinaryTree<E> paramBinaryTree)
{
BinaryTree localBinaryTree = this.left;
this.left = paramBinaryTree;
return localBinaryTree;
}
public BinaryTree<E> setRight(BinaryTree<E> paramBinaryTree)
{
BinaryTree localBinaryTree = this.right;
this.right = paramBinaryTree;
return localBinaryTree;
}
public String toString()
{
StringBuilder localStringBuilder = new StringBuilder("" + this.root);
if (!isLeaf())
{
localStringBuilder.append("(");
if (this.left != null) {
localStringBuilder.append(this.left);
}
if (this.right != null) {
localStringBuilder.append("," + this.right);
}
localStringBuilder.append(")");
}
return localStringBuilder + "";
}
public boolean isLeaf()
{
return (this.left == null) && (this.right == null);
}
}

the TreeSet, according to your code, was never initialized
TreeSet ts = new TreeSet();
I think that should fix it...

Related

Binary tree in java with getters and setters

I'm trying to create binary tree by following example 1 where tree is made without getters and setters. I would like to create it with geeters and setters but I'm stuck on line with recursion. How can I call recursion function with/inside setter? Here is the code..
p.s. Tree class pastebin
public class TreeF {
Tree root;
public void insert(int value) {
if (root==null) {
root = new Tree(value);
return;
}
Tree current = root;
if (value < current.getData() ) {
if (current.getLeft()==null) {
current.setLeft(new Tree (value));
}else {
// call insert method inside current.left object [currrent.left(insert(value))]
current=current.getLeft();
insert (value);
}
}
else {
if (current.getRight()==null) {
current.setRight(new Tree (value));
}else {
current=current.getRight();
insert (value);
}
}
}
}
Change insert(value) to current.insert(value)
To implement recursion, you need to change a parameter(or multiple) so you can go to the stopping condition after some recursive calls.
In your code, you called the method insert that was part of the same object. And not its left/right subtree. In other words, the recursion never ends, because you don't visit the child subtrees.
public class Tree {
private int data;
private Tree left;
private Tree right;
public Tree (int data) {
this.data=data;
}
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
public Tree getLeft() {
return left;
}
public void setLeft(Tree left) {
this.left = left;
}
public Tree getRight() {
return right;
}
public void setRight(Tree right) {
this.right = right;
}
public void insert(int value) {
if (value < getData()) {
if (getLeft() == null) {
setLeft(new Tree(value));
} else {
getLeft().insert(value);
}
} else {
if (getRight() == null) {
setRight(new Tree(value));
} else {
getLeft().insert(value);
}
}
}
}
You do not need a current field or a root. Here's your insert method greatly simplified to demonstrate.
public class Tree {
final int data;
Tree left;
Tree right;
public Tree(int value) {
data = value;
}
public void insert(int value) {
if (value < data) {
if (left == null) {
left = new Tree(value);
} else {
left.insert(value);
}
} else {
if (right == null) {
right = new Tree(value);
} else {
right.insert(value);
}
}
}
}

Having trouble searching binary search tree

Trying to search the binary search tree but there seems I cannot figure out why the there statement is not working, the method calls for the input of a String, but it says that a Node is required. Any suggestions how to fix this?
Here is the Node Class:
public class Node
{
String key;
Node left, right;
public Node(String entry)
{
key = entry;
left = right = null;
}
public Node getLeft()
{
return left;
}
public Node getRight()
{
return right;
}
public String getKey(String entry)
{
if(this.key.equals(key))
{
return key;
}
if(entry.compareTo(this.key) < 0)
{
return left == null ? null : left.getKey(entry);
}
else
{
return right == null ? null : right.getKey(entry);
}
}
public void setLeft(Node left)
{
this.left = left;
}
public void setRight(Node right)
{
this.right = right;
}
}
Here is my Binary Search Tree:
public class BinarySearchTree
{
Node root;
public BinarySearchTree()
{
root = null;
}
public void insert(String key)
{
root = insertRec(root, key);
}
public Node insertRec(Node root, String key)
{
if(root == null)
{
root = new Node(key);
return root;
}
if(key.compareTo(root.toString()) == -1)
{
root.setLeft(insertRec(root.getLeft(), key));
}
else if(key.compareTo(root.toString()) == 1)
{
root.setRight(insertRec(root.getRight(), key));
}
return root;
}
public Node search(String key)
{
return root == null ? null : root.getKey(key);
}
public void printPostOrder(Node node)
{
if(node == null)
return;
printPostOrder(root.getLeft());
printPostOrder(node.getRight());
System.out.print(node.getKey() + ", ");
}
public void printInOrder(Node node)
{
if(node == null)
return;
printInOrder(node.getLeft());
System.out.print(node.getKey() + ", ");
printInOrder(node.getRight());
}
public void printPreOrder(Node node)
{
if(node == null)
return;
System.out.print(node.getKey() + ", ");
printPreOrder(node.getLeft());
printPreOrder(node.getRight());
}
public void printPostOrder()
{
printPostOrder(root);
}
public void printInOrder()
{
printInOrder(root);
}
public void printPreOrder()
{
printPreOrder(root);
}
}
Any and all help is much appreciated if you need more information please let me know.
whats up ?
your code is wrong in the class node in method getKey change your return String to Node and your if equals and return to this.
Ex:.
public Node getKey(String entry)
{
if(this.key.equals(entry))
{
return this;
}
}
if you change this your code work.
Full class BinarySearchTree tested ok
public class BinarySearchTree
{
Node root;
public BinarySearchTree()
{
root = null;
}
public void insert(String key)
{
root = insertRec(root, key);
}
public Node insertRec(Node root, String key)
{
if(root == null)
{
root = new Node(key);
return root;
}
if(key.compareTo(root.toString()) == -1)
{
root.setLeft(insertRec(root.getLeft(), key));
}
else if(key.compareTo(root.toString()) == 1)
{
root.setRight(insertRec(root.getRight(), key));
}
return root;
}
public Node search(String key)
{
return root == null ? null : root.getKey(key);
}
public void printPostOrder(Node node)
{
if(node == null)
return;
printPostOrder(root.getLeft());
printPostOrder(node.getRight());
System.out.print(node.getKey("") + ", ");
}
public void printInOrder(Node node)
{
if(node == null)
return;
printInOrder(node.getLeft());
System.out.print(node.getKey("") + ", ");
printInOrder(node.getRight());
}
public void printPreOrder(Node node)
{
if(node == null)
return;
System.out.print(node.getKey("") + ", ");
printPreOrder(node.getLeft());
printPreOrder(node.getRight());
}
public void printPostOrder()
{
printPostOrder(root);
}
public void printInOrder()
{
printInOrder(root);
}
public void printPreOrder()
{
printPreOrder(root);
}
public static void main (String args[]){
BinarySearchTree bs = new BinarySearchTree();
bs.insert("A");
bs.search("A");
}
}
and Node complete
public class Node
{
String key;
Node left, right;
public Node(String entry)
{
key = entry;
left = right = null;
}
public Node getLeft()
{
return left;
}
public Node getRight()
{
return right;
}
public Node getKey(String entry)
{
if(this.key.equals(key))
{
return this;
}
if(entry.compareTo(this.key) < 0)
{
return left == null ? null : left.getKey(entry);
}
else
{
return right == null ? null : right.getKey(entry);
}
}
public void setLeft(Node left)
{
this.left = left;
}
public void setRight(Node right)
{
this.right = right;
}
}

Why is the recursive insertion method of the BST not working

I wrote the following code to implement the recursive insert method for the BST. But when I print the tree in walk over order it prints the original tree before insertion. It seems as if the element was not inserted. Please help me out. Thanks in advance. Also please suggest the change in code. By the way, the intial tree in walk over order is 2 5 5 6 7 8.
package DataStructures;
class TreeNode {
private TreeNode parent;
private TreeNode childLeft;
private TreeNode childRight;
private int key;
public TreeNode(){
}
public TreeNode(int key) {
this(key, null);
}
public TreeNode(int key, TreeNode parent) {
this(key, parent, null, null);
}
public TreeNode(int key, TreeNode parent, TreeNode childLeft, TreeNode childRight) {
this.key = key;
this.parent = parent;
this.childLeft = childLeft;
this.childRight = childRight;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public TreeNode getParent() {
return parent;
}
public void setParent(TreeNode parent) {
this.parent = parent;
}
public TreeNode getChildLeft() {
return childLeft;
}
public void setChildLeft(TreeNode childLeft) {
this.childLeft = childLeft;
}
public TreeNode getChildRight() {
return childRight;
}
public void setChildRight(TreeNode childRight) {
this.childRight = childRight;
}
}
public class BinarySearchTreeBasicTest {
private static class BinarySearchTree {
private TreeNode root;
private TreeNode maxNode = new TreeNode(0);
public BinarySearchTree(TreeNode root) {
this.root = root;
}
public void printTheTreeInOrderWalk(TreeNode x) {
if (x != null) {
printTheTreeInOrderWalk(x.getChildLeft());
System.out.print(x.getKey() + " ");
printTheTreeInOrderWalk(x.getChildRight());
}
}
public void insertNode(TreeNode node, int key){
if (node == null){
node = new TreeNode(key);
}
else{
if (node.getKey() > key){
insertNode(node.getChildLeft(), key);
} else if (node.getKey() < key){
System.out.println("k");
insertNode(node.getChildRight(), key);
} else{
// dont do anything
}
}
}
}
public static void main(String[] args) {
TreeNode rootNode = new TreeNode(6);
BinarySearchTree tree = new BinarySearchTree(rootNode);
TreeNode node1 = new TreeNode(5);
TreeNode node2 = new TreeNode(7);
rootNode.setChildLeft(node1);
rootNode.setChildRight(node2);
node1.setParent(rootNode);
node2.setParent(rootNode);
TreeNode node3 = new TreeNode(2);
TreeNode node4 = new TreeNode(5);
node1.setChildLeft(node3);
node1.setChildRight(node4);
node3.setParent(node1);
node4.setParent(node1);
TreeNode node5 = new TreeNode(8);
node5.setParent(node2);
node2.setChildRight(node5);
tree.insertNode(rootNode, 3);
tree.printTheTreeInOrderWalk(rootNode);
}
}
In your insertNode() method, you are just creating a new node; you are never adding the newly created node to its parent. You should check whether you are going to insert here or not or you should return the newly returned node and set it accordingly.
If you don't want too much deviation from your current program, you can make the following changes.
public void insertNode(TreeNode node, int key) {
if (node.getKey() > key) {
if (node.left == null) { //check if you want to insert the node here
TreeNode newNode = new TreeNode(key);
node.left = newNode;
} else {
insertNode(node.getChildLeft(), key);
}
} else if (node.getKey() < key) {
if(node.right == null){ //check if you want to insert the node here
TreeNode newNode = new TreeNode(key);
node.right = newNode;
} else {
insertNode(node.getChildRight(), key);
}
} else {
// don't do anything
}
}
In Java, parameters are passed by value. In insertNode, if you don't do anything else with the node, the line node = new TreeNode(key); will not do anything useful.
The typical implementation of an insertion in a tree works by returning the TreeNode that will replace the previous one:
private TreeNode insertNode(TreeNode node, int key){
if (node == null){
node = new TreeNode(key);
}
else{
if (node.getKey() > key){
node.setChildLeft(insertNode(node.getChildLeft(), key));
} else if (node.getKey() < key){
node.setChildRight(insertNode(node.getChildRight(), key));
} else{
// dont do anything
}
}
return node;
}
Going a bit further, the previous method should actually be private. The public method should look like this:
public void insertNode(int key){
root = insertNode(root, key);
}

Binary Tree toString method -_-

Why is it outputting null for parent and childs!? The logic seems fine to me...
It shouldn't be printing out null for the left, right, and parent since they are updated with left = left.toString(); etc.
The main method:
public class TreeInfo
{
public static void main(String[] args)
{
BinaryTree<Integer> left = new BinaryTree<Integer>(5);
System.out.println(left);
BinaryTree<Integer> right = new BinaryTree<Integer>(9);
BinaryTree<Integer> parent = new BinaryTree<Integer>(1);
BinaryTree<Integer> a = new BinaryTree<Integer>(parent, 5, left, right);
System.out.println(a);
}
}
.
The methods class:
import java.math.*;
import java.lang.*;
import java.util.*;
public class BinaryTree<E> implements BinaryTreeNode<E>
{
protected E data;
protected BinaryTreeNode<E> parent;
protected BinaryTreeNode<E> left;
protected BinaryTreeNode<E> right;
public BinaryTree(BinaryTree<E> parent, E data, BinaryTree<E> left, BinaryTree<E> right)
{
this.data = data;
this.left = left;
this.right = right;
}
public BinaryTree(E data)
{
this(null, data, null, null);
}
public E getData()
{
return this.data;
}
public BinaryTreeNode<E> getParent()
{
return this.parent;
}
public boolean isEmpty()
{
return data == null;
}
public boolean isLeaf()
{
return left == null && right == null;
}
public boolean hasLeft()
{
return left != null;
}
public boolean hasRight()
{
return right != null;
}
public int getNONodes()
{
int count = 1;
if (hasLeft())
{
count += left.getNONodes();
}
if (hasRight())
{
count += right.getNONodes();
}
return count;
}
public String toString() {
if (isLeaf()) {
return data.toString();
}
else {
String root = "null", parent = "null", left = "null", right = "null";
root = data.toString();
if (left != null) {
left = left.toString();
}
if (right != null) {
right = right.toString();
}
if (parent != null)
{
parent = parent.toString();
}
return root + " (" + parent + ", " + left + ", " + right + ")";
}
}
}
inferface:
public interface BinaryTreeNode<E>
{
E getData(); // Returns a reference to data and a reference to its left and right subtrees.
BinaryTreeNode<E> getParent(); // Returns the parent of this node, or null if this node is a root.
boolean isEmpty(); // returns false if the tree is non-empty and true if it is.
boolean hasLeft();
boolean hasRight();
boolean isLeaf();
int getNONodes(); // returns total number of nodes in the Binary Tree.
String toString();
}
output when ran:
5
5 (null, null, null)
Process completed.
In your toString method you're not referencing the left, right and parent objects as class member fields but as the String local variables declared in the method. Use this.left instead:
if(this.left != null) {
left = this.left.toString();
}
In your constructor:
public BinaryTree(BinaryTree<E> parent, E data, BinaryTree<E> left, BinaryTree<E> right)
{
this.data = data;
this.left = left;
this.right = right;
}
You aren't doing anything with the parent. therefore you end up with small trees that aren't connected.
you need to add the line:
public BinaryTree(BinaryTree<E> parent, E data, BinaryTree<E> left, BinaryTree<E> right)
{
this.data = data;
this.left = left;
this.right = right;
this.parent = parent;
}

Regarding a method "cannot be resolved to a type" error

I am trying to create null nodes at the bottom of a RBTree and want to instantiate EMPTY as an empty node.
this the line that has the error:
final private Node<E> EMPTY = new Empty();
And the empty class:
private class Empty extends Node<E> {
public Empty() {
red = false;
}
public Node<E> add(E data) {
count++;
return new Node<E>(data);
}
public Node<E> getNode(E data) {
return null;
}
}
I know it has something to do with the constructor but I can't zero in on it.
I have tried searching but most everything I come across on this site is related to android programming and/or some other language I'm not familiar with. I've tried the following:
(Node) casting the new Empty(); then realized it was obviously not that.
and working with the class seeing if public would work.
Aside from programming changes i've also tried the solutions offered here:
http://philip.yurchuk.com/software/eclipse-cannot-be-resolved-to-a-type-error/
But to no success.
Sorry if this question is out of place, and thank you for your time!
complete code:
package data_structures;
public class RedBlackTree<E extends Comparable<E>> {
private Node<E> root;
private int count = 0;
final private Node<E> EMPTY = new Empty<E>();
public RedBlackTree() {
root = EMPTY;
}
public void add(E data) {
root = root.add(data);
count++;
root.red = false;
}
public boolean find(E data) {
return root.getNode(data) != null;
}
private class Node<E> {
public E data;
public boolean red;
public Node<E> leftChild;
public Node<E> rightChild;
/** Used by Empty */
protected Node() {
assert EMPTY == null;
}
/** Nodes always begin red */
public Node(E k) {
data = k;
red = true;
leftChild = (Node<E>) EMPTY;
rightChild = (Node<E>) EMPTY;
}
private boolean isRed() {
return red;
}
public int height(){
return 0; //returns the counts binary left most bit position to determine the height.
}
public Node<E> add(E newData) {
if(((Comparable<E>) newData).compareTo(data) == -1) {
count++;
leftChild = leftChild.add(newData);
return leftChild;
}
if(((Comparable<E>) newData).compareTo(data) == +1){
count++;
rightChild = rightChild.add(newData);
return rightChild;
}
if(((Comparable<E>) newData).compareTo(data) == 0){
return this;
}
if (leftChild.isRed() && leftChild.leftChild.isRed()) {
return balance(leftChild.leftChild, leftChild, this,
leftChild.leftChild.rightChild, leftChild.rightChild);
} else if (leftChild.isRed() && leftChild.rightChild.isRed()) {
return balance(leftChild, leftChild.rightChild, this,
leftChild.rightChild.leftChild, leftChild.rightChild.rightChild);
} else if (rightChild.isRed() && rightChild.leftChild.isRed()) {
return balance(this, rightChild.leftChild, rightChild,
rightChild.leftChild.leftChild, rightChild.leftChild.rightChild);
} else if (rightChild.isRed() && rightChild.rightChild.isRed()) {
return balance(this, rightChild, rightChild.rightChild,
rightChild.leftChild, rightChild.rightChild.leftChild);
}
return this;
}
/** Returns the node for this key, or null. */
public Node<E> getNode(E newData) {
if(((Comparable<E>) newData).compareTo(data) == -1){
return leftChild.getNode(newData);
}
if(((Comparable<E>) newData).compareTo(data) == +1){
return rightChild.getNode(newData);
}
else{
return this;
}
}
private class Empty<E> extends Node<E> {
public Empty() {
red = false;
}
public Node<E> add(E data) {
count++;
return new Node<E>(data);
}
public Node<E> getNode(E data) {
return null;
}
}
private Node<E> balance(Node<E> a, Node<E> b, Node<E> c, Node<E> d, Node<E> e) {
a.rightChild = d;
b.leftChild = a;
b.rightChild = c;
c.leftChild = e;
a.red = false;
b.red = true;
c.red = false;
return b;
}
}
}
You can't write
Node<E> EMPTY = new Empty<E>();
because E is a generic type. You can only create an object with actual class, such as:
Node<String> EMPTY = new Empty<String>()
If you know what you are doing, you can do an ugly trick that should work with a warning
Node<E> EMPTY = new Empty();
Also, move the Empty class outside of Node.

Categories

Resources