The program is running well in for the other method. However in my deletion, espeacially in one case that when i'm going to delete a node which has 2 children i can get to perform the transplant part but no matter what i tried i could not get rid of the right child which i just replaced with the its parents.
i have tried to set it to null and return it right away when it set to null(which it should be deleted)
the print methods are working perfectly fine but not the deletion one.
this is my output:
INSERT 4 E 3 E 6 E 2 H 1 T 5 Y 7 S
POSTORDER
THEYSEE
INORDER
THEEYES
DELETE 6 4 1 2
PREORDER
YESS
EXIT
so the problem now is why the hell the key 7 get duplicated it never get to deleted while i'm trying to move its data from 7 to 6.
import java.util.*;
public class Main {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
boolean done = false;
BinarySearchTree myTree = new BinarySearchTree();
while (!done && s.hasNextLine()) {
String line = s.nextLine();
Scanner ls = new Scanner(line);
String token = ls.next();
switch (token.toUpperCase()) {
case "INSERT":
while(ls.hasNext()) {
myTree.insert(Integer.parseInt(ls.next()), ls.next());
}
continue;
case "INORDER":
myTree.inorderSearch();
System.out.println();
continue;
case "DELETE":
while(ls.hasNext()) {
myTree.deleteNode(myTree.root,Integer.parseInt(ls.next()));
}
continue;
case "PREORDER":
myTree.preorder();
System.out.println();
continue;
case "POSTORDER":
myTree.postorder();
System.out.println();
continue;
case "EXIT":
done = true;
}
}
}
}
//BINARY SEARCH TREE CLASS
class BinarySearchTree {
class Node {
int key;
String data;
Node right, left;
public Node(int item, String data) {
this.key = item;
this.data = data;
this.left = this.right = null;
}
public void setKey(int key) {
this.key = key;
}
public void setData(String data) {
this.data = data;
}
public void setRight(Node right) {
this.right = right;
}
public void setLeft(Node left) {
this.left = left;
}
public Node getRight() {
return right;
}
public Node getLeft() {
return left;
}
public int getKey() {
return key;
}
public String getData() {
return data;
}
}
Node root;
BinarySearchTree() {
this.root = null;
}
private Node insertHelper(Node root, int key, String data) {
if (root == null) {
root = new Node( key, data);
return root;
}
if (key < root.key)
root.left = insertHelper(root.left, key, data);
else if (key > root.key)
root.right = insertHelper(root.right, key, data);
return root;
}
void insert(int key, String data) {
root = insertHelper(root, key, data);
}
void inorderSearch() {
inorderSearchHelper(root);
}
private void inorderSearchHelper(Node root) {
if (root != null) {
inorderSearchHelper(root.left);
System.out.print(root.data);
inorderSearchHelper(root.right);
}
}
public void postorder(){
postorderHelper(root);
}
private void postorderHelper(Node root) {
if (root == null)
return;
postorderHelper(root.left);
postorderHelper(root.right);
System.out.print(root.data);
}
public void preorder(){
preorderHelper(root);
}
private void preorderHelper(Node node) {
if (node == null)
return;
System.out.print(node.data);
preorderHelper(node.left);
preorderHelper(node.right);
}
// DELETE FKING NODEs!
/*private void transplant(Node root,Node u, Node v){
if(u. == )
}*/
public static Node minimumElement(Node root) {
if (root.left == null)
return root;
else {
return minimumElement(root.left);
}
}
public static Node deleteNode(Node root, int key) {
if (root == null)
return null;
if (root.key > key) {
root.left = deleteNode(root.left, key);
} else if (root.key < key) {
root.right = deleteNode(root.right, key);
} else {
// if nodeToBeDeleted have both children
if (root.left != null && root.right != null) {
Node temp = root;
// Finding minimum element from right
Node minNodeForRight = minimumElement(temp.right);
// Replacing current node with minimum node from right subtree
root.data = minNodeForRight.data;
// Deleting minimum node from right now
deleteNode(root.right, minNodeForRight.key);
}
// if nodeToBeDeleted has only left child
else if (root.left != null) {
root = root.left;
}
// if nodeToBeDeleted has only right child
else if (root.right != null) {
root = root.right;
}
// if nodeToBeDeleted do not have child (Leaf node)
else
root = null;
}
return root;
}
}
so this is the right output:
INSERT 4 E 3 E 6 E 2 H 1 T 5 Y 7 S
POSTORDER
THEYSEE
INORDER
THEEYES
DELETE 6 4 1 2
PREORDER
YES
EXIT
Related
When I use insert() to inset new nodes into the binary tree it only inserts the new nodes on the place of child nodes even when root node already have left and right child. It is not visiting the child nodes to make deeper levels of binary tree.
Sorry for the bad English.
class Node
{
int key;
String value;
Node lc = null;
Node rc = null;
Node(int k,String v)
{
key = k;
value = v;
}
public String toString()
{
return value + "is" + key;
}
}
class BT
{
Node root;
public void insert(int k,String v)
{
Node newnode = new Node(k,v);
if(root == null)
{
System.out.println("root");
root = newnode;
return;
}
Node n = root;
while(n != null)
{
if(newnode.key <= n.key)
{
n = n.lc;
System.out.println("left");
if(n==null){n = newnode; break;}
}
else
{
n = n.rc;
System.out.println("right");
if(n==null){n = newnode; break;}
}
}
System.out.println("loop ended");
return;
}
}
public class test
{
public static void main(String arg[])
{
BT list = new BT();
list.insert(19,"one");
list.insert(67,"sixtyseven");
list.insert(5,"five");
list.insert(12,"twelve");
list.insert(67,"sixtyseven");
}
}
You never change the lc and rc links. Try something like this:
if(newnode.key <= n.key)
{
if(n.lc==null){n.lc = newnode; break;}
n = n.lc;
System.out.println("left");
}
else
{
if(n.rc==null){n.rc = newnode; break;}
n = n.rc;
System.out.println("right");
}
What about using recursion? It's much more clear to realise.
public final class BinaryTree {
private static final boolean ADD_TO_PARENT = true;
private static final boolean ALREADY_ADDED = false;
private Node root;
public void add(int key, String value) {
Node node = new Node(key, value);
if (add(node, root) == ADD_TO_PARENT)
root = node;
}
private static boolean add(Node node, Node parent) {
if (parent == null)
return ADD_TO_PARENT;
if (node.key <= parent.key) {
if (add(node, parent.left) == ADD_TO_PARENT)
parent.left = node;
} else if (add(node, parent.right) == ADD_TO_PARENT)
parent.right = node;
return ALREADY_ADDED;
}
public static final class Node {
private final int key;
private final String value;
private Node left;
private Node right;
public Node(int key, String value) {
this.key = key;
this.value = value;
}
#Override
public String toString() {
return value + " is " + key;
}
}
}
I was able to implement a Boolean insert method for a binary search tree. It takes a generic data and inserts a key into the BST. My code does not allow duplicates, and returns false if a key is already presented in the BST. It returns true if the insertion is successful.
The problem is that, I think its not increment the number of elements present in the BST and is only able to reach 2 elements.
I have tried to debug it and see why my output and expected is off by one.
Here is my constructors and methods
public class BSTree<T extends Comparable<? super T>> implements Iterable {
private int nelems;
private BSTNode root;
private BSTNode curr;
private BSTNode keyHere;
protected class BSTNode {
T key;
LinkedList<T> dataList;
BSTNode left;
BSTNode right;
public BSTNode(BSTNode left, BSTNode right, LinkedList<T> dataList, T key) {
//TODO
this.left = left;
this.right = right;
this.key = key;
setDataList(dataList);
}
public BSTNode(BSTNode left, BSTNode right, T key) {
//TODO
this.left = left;
this.right = right;
this.key = key;
this.dataList = new LinkedList<T>();
}
public T getKey() {
//TODO
return this.key;
}
public BSTNode getLeft() {
//TODO
return this.left;
}
public BSTNode getRight() {
//TODO
return this.right;
}
public LinkedList<T> getDataList() {
//TODO
return this.dataList;
}
public void setleft(BSTNode newleft) {
//TODO
this.left = newleft;
}
public void setright(BSTNode newright) {
//TODO
this.right = newright;
}
public void setDataList(LinkedList<T> newData) {
//TODO
this.dataList = newData;
}
public void addNewInfo(T data) {
//TODO
if (data != null)
{
getDataList().addLast(data);
}
}
public boolean removeInfo(T data) {
return dataList.remove(data);
}
}
public BSTree() {
//TODO
root = null;
nelems = 0;
curr = null;
keyHere = null;
}
Here is my code for insertion
public boolean insert(T key) {
if (key == null)
{
throw new NullPointerException();
}
if (findKey(key)) // this method returns true if key is in BST
{
return false;
}
if (getSize() == 0)
{
LinkedList<T> linked = new LinkedList<T>();
BSTNode node = new BSTNode(null, null, linked,key);
root = node;
curr = root;
nelems = 1;
}
else
{
if (curr.getKey().compareTo(key) < 0)
{
if(curr.getRight() != null)
{
curr = curr.getRight();
insert(key);
}
else
{
LinkedList<T> linked = new LinkedList<T>();
BSTNode node = new BSTNode(null,null,linked,key);
curr.setright(node);
nelems += 1 ;
curr = root;
}
}
else
{
if (curr.getLeft() != null)
{
curr = curr.getLeft();
insert(key);
}
else
{
LinkedList<T> linked = new LinkedList<T>();
BSTNode node = new BSTNode(null,null,linked,key);
curr.setleft(node);
curr = root;
nelems += 1;
}
}
}
return true;
}
public boolean findKey(T key) {
if (key == null)
{
throw new NullPointerException();
}
if (getSize() == 0)
{
return false;
}
else if(curr.getKey().compareTo(key)!= 0)
{
if(curr.getKey().compareTo(key) < 0)
{
if (curr.getRight() != null)
{
curr = curr.getRight();
findKey(key);
}
else
{
this.curr = root;
return false;
}
}
else
{
if (curr.getLeft() != null)
{
curr = curr.getLeft();
findKey(key);
}
else
{
this.curr = root;
return false;
}
}
}
else
{
this.keyHere = curr;
this.curr = root;
return true;
}
return true;
}
When I would insert a value to a tree it keeps track of the first 2 elements but after adding the third one it stops increment element for some reason.
here is my testers
public class BSTreeTester{
BSTree<Integer> tree1;
public void setUp() throws Exception {
tree1 = new BSTree<Integer>();
}
public void testinsert() {
tree1.insert(new Integer(100));
assertEquals("The size of the tree should be 1", 1, tree1.getSize());
assertEquals("The root of the tree should be 100", 100,
(int)tree1.getRoot().getKey());
tree1.insert(new Integer(200));
assertEquals("The size of the tree shoul dbe 2", 2, tree1.getSize());
assertEquals("The root of the tree should still be 100", 100,
(int)tree1.getRoot().getKey());
tree1.insert(new Integer(300));
assertEquals("The size of the tree should be 3", 3, tree1.getSize());
assertEquals("The root of the tree should still be 100", 100,
(int)tree1.getRoot().getKey());
}
When inserting the 3rd new integer the expected should be 3, but its giving me 2.
I have a method to insert nodes in a BST according to the alphabetical order, but I have an infinite loop when I compare the 2 strings I think that the value never changes when it passes the comparison so it's comparing again with the same values resulting in an infinite loop. I think that the aux and Tnodes are not updating the values with the recursive method so it's comparing the same values over and over.
class BST {
BSTNode root;
public BST() {
root = null;
}
BSTNode aux = new BSTNode();
BSTNode insertNames(BSTNode T , int data, String name, double salary) {
if (root == null) {
T = new BSTNode();
T.setName(name);
root = T;
} else {
aux = root;
if (name.compareTo(aux.getName()) < 0)
aux.setLeft(insertNames(aux.getLeft(),data, name, salary));
else if (name.compareTo(aux.getName()) >= 0)
aux.setRight(insertNames(aux.getRight(),data, name, salary));
}
return T;
}
}
class Main{
public static void main(String[] args){
BST alpha=new BST();
BSTNode root = new BSTNode();
alpha.insertNames(root, 0, "Roy", 0);
alpha.insertNames(root, 0, "Joseph", 0);
}
}
package com.gati.dsalgo.string;
class BST {
BSTNode root;
public BST() {
root = null;
}
void insertNames(int data, String name, double salary) {
root = insertNames(root, data, name, salary);
}
BSTNode insertNames(BSTNode root, int data, String name, double salary) {
if (root == null) {
root = new BSTNode();
root.setName(name);
return root;
}
if (name.compareTo(root.getName()) < 0)
root.setLeft(insertNames(root.getLeft(), data, name, salary));
else if (name.compareTo(root.getName()) >= 0)
root.setRight(insertNames(root.getRight(), data, name, salary));
return root;
}
}
public class Main1 {
public static void main(String[] args) {
BST alpha = new BST();
alpha.insertNames(0, "Roy", 0);
alpha.insertNames(0, "Joseph", 0);
System.out.println("hello");
}
}
class BSTNode {
private String name;
BSTNode left;
BSTNode right;
public void setName(String name) {
this.name = name;
}
public void setRight(BSTNode right) {
this.right = right;
}
public void setLeft(BSTNode left) {
this.left = left;
}
public BSTNode getRight() {
return right;
}
public BSTNode getLeft() {
return left;
}
public String getName() {
return name;
}
}
Please return the node in recursion end logic.
/* If the tree is empty, return a new node */
if (root == null) {
root = new BSTNode();
root.setName(name);
return root;
}
/* Otherwise, recur down the tree */
if (name.compareTo(root.getName()) < 0)
root.setLeft(insertNames(root.getLeft(), data, name, salary));
else if (name.compareTo(aux.getName()) >= 0)
root.setRight(insertNames(root.getRight(), data, name, salary));
/* return the (unchanged) node pointer */
return root;
or it can be solve iterative way
if (localRoot == null) {
newNode = new Node < V > (value, null);
root = newNode;
size++;
return true;
}
if (comparator != null) {
//Some code
} else {
Comparable << ? super V > v = (Comparable << ? super V > ) value;
while (localRoot != null) {
parent = localRoot;
cmp = v.compareTo(localRoot.getValue());
if (cmp < 0) {
localRoot = localRoot.getLeftChield();
} else if (cmp > 0) {
localRoot = localRoot.getRightChield();
} else {
localRoot.incrementBy(nCopies);
return true;
}
}
newNode = new Node < V > (value, parent);
if (cmp < 0) {
parent.setLeftChield(newNode);
} else if (cmp > 0) {
parent.setRightChield(newNode);
}
size++;
return true;
}
return false;
So I was given an assignment in which I had to find and fix many errors in a somewhat large and sloppy code. I'm down to what looks to be the last one and I can't find the solution to this one. I've read similar scenarios where people get the same mistake but I can't relate them to my code. This is where I get the error: Temp = new BinaryNode(AId,AValue); saying
constructor BinaryNode in class BinaryNode cannot be applied to given
types;
Btree Class
package evidencia2datos;
public class BTree {
private BinaryNode Root;
private int NoOfNodes;
private BTree()
{
Root = null;
NoOfNodes = 0;
}
//operaciones
public boolean IsEmpty() //busca valor en NoOfNodes
{
return(NoOfNodes == 0);
}
public BinaryNode gRoot()
{
return Root;
}
public int Count() //valor de NoOfNodes
{
return NoOfNodes;
}
//size del arbol
public int Size(BinaryNode ATree)
{
if (ATree == null)
return 0;
else
return(1 + Size(ATree.gLeft()) + Size(ATree.gRight()));
}
//niveles
public int Height(BinaryNode ATree)
{
if (ATree == null)
return 0;
else
return (1 + Math.max(Height(ATree.gLeft()), Height(ATree.gRight())));
}
//traversales
public void PreOrder(BinaryNode ATree)
{
if (ATree != null)
{
System.out.println(ATree.gData());
PreOrder(ATree.gLeft());
PreOrder(ATree.gRight());
}
}
public void InOrder(BinaryNode ATree)
{
if (ATree != null)
{
InOrder(ATree.gLeft());
System.out.println(ATree.gData());
InOrder(ATree.gRight());
}
}
public void PostOrder(BinaryNode ATree)
{
if (ATree != null)
{
PostOrder(ATree.gLeft());
PostOrder(ATree.gRight());
System.out.println(ATree.gData());
}
}
//insertar valores
public void Insert(int AId, Object AValue)
{
BinaryNode Temp,Current,Parent;
if(Root == null)//tree is empty
{
Temp = new BinaryNode(AId,AValue);
Root = Temp;
NoOfNodes++;
}
else//tree is not empty
{
Temp = new BinaryNode(AId,AValue);
Current = Root;
while(true)//never ending while loop
{
Parent = Current;
if(AId < Current.gKey())
{//go left
Current = Current.gLeft();
if (Current == null)
{
Parent.sLeft(Temp);
NoOfNodes++;
return;//jump out of loop
}
}
else
{ //go right
Current = Current.gRight();
if(Current == null)
{
Parent.sRight(Temp);
NoOfNodes++;
return;
}
}
}
}
}
//search
public BinaryNode Find(int AKey)
{
BinaryNode Current = null;
if(!IsEmpty())
{
Current = Root; //start search at top of tree
while(Current.gKey() != AKey)
{
if(AKey < Current.gKey())
Current = Current.gLeft();
else
Current = Current.gRight();
if(Current == null)
return null;
}
}
return Current;
}
//succesor
public BinaryNode GetSuccessor(BinaryNode ANode)
{
BinaryNode Current,Successor,SuccessorParent;
Successor = ANode;
SuccessorParent = ANode;
Current = ANode.gRight();
while(Current !=null)
{
SuccessorParent = Successor;
Successor = Current;
Current = Current.gLeft();
}
if(Successor != ANode.gRight())
{
SuccessorParent.sLeft(Successor.gRight());
Successor.sRight(ANode.gRight());
}
return Successor;
}
public boolean Delete (int AKey)
{
BinaryNode Current, Parent;
boolean IsLeftChild = true;
Current = Root;
Parent = Root;
while (Current.gKey() != AKey)
{
Parent = Current;
if (AKey < Current.gKey())
{
IsLeftChild = true;
Current = Current.gLeft();
}
else
{
IsLeftChild = false;
Current = Current.gRight();
}
if(Current == null)
return false;
}
// if no children delete the node
if (Current.gLeft() == null && Current.gRight() == null)
{
if (Current == Root)
Root = Current.gLeft();
else
if (IsLeftChild)
Parent.sLeft(Current.gRight());
else
Parent.sRight(Current.gRight());
}
// if no right child replace with left subtree
else
{
if (Current.gRight() == null)
{
if (Current == Root)
Root = Current.gRight();
else
if (IsLeftChild)
Parent.sLeft(Current.gLeft());
else
Parent.sRight(Current.gLeft());
}
// if no left child replace with right subtree
else
{
if (Current.gLeft() == null)
{
if (Current == Root)
Root = Current.gLeft();
else
if (IsLeftChild)
Parent.sLeft(Current.gRight());
else
Parent.sRight(Current.gRight());
}
// two children so replace in order of successor
else
{
BinaryNode Successor = GetSuccessor(Current);
if (Current == Root)
Root = Successor;
else
if (IsLeftChild)
Parent.sLeft(Successor);
else
Parent.sRight(Successor);
Successor.sLeft(Current.gLeft());
}
}
}
NoOfNodes--;
return true;
}
public static void main(String[] args) {
BTree MyTree = new BTree();
BinaryNode NodeAt;
MyTree.Insert(12,"Jorge");
MyTree.Insert(4,"Andres");
MyTree.Insert(11,"Javier");
MyTree.Insert(1,"Jose");
MyTree.Insert(100,"Paty");
MyTree.Delete(1);
MyTree.InOrder(MyTree.gRoot());
NodeAt = MyTree.Find(11);
if(NodeAt !=null)
System.out.println("Data in Node with Key 11 = " + NodeAt.gData());
System.exit(0);
}
}
BinaryNode Class
package evidencia2datos;
public class BinaryNode {
private int Key;
private Object Data;
private BinaryNode Left;
private BinaryNode Right;
public BinaryNode()
{
java.util.Scanner scaniar = new java.util.Scanner(System.in);
System.out.print("Enter in Key Value: ");
Key = scaniar.nextInt();
System.out.print("Enter in data: ");
Data = scaniar.nextInt();
Left = null;
Right = null;
}
//get
public int gKey()
{
return Key;
}
public Object gData()
{
return Data;
}
public BinaryNode gLeft()
{
return Left;
}
public BinaryNode gRight()
{
return Right;
}
//set
public void sKey(int AValue)
{
Key = AValue;
}
public void sData(Object AValue)
{
Data = AValue;
}
public void sLeft( BinaryNode AValue)
{
Left = AValue;
}
public void sRight( BinaryNode AValue)
{
Right = AValue;
}
}
You can create a new BinaryNode constructor which takes two arguments
BinaryNode (){
...
}
//Este es el nuevo constructor, como se puede observar
//toma dos argumentos
BinaryNode (int k, Object d){
key = k;
data = d;
...
}
I hope this will help you.
I am a bit stuck trying to create a print the path to TreeNode method. Not quite sure where I went wrong but I think it might be in the 2nd else.
code:
public static ArrayList<Integer> printPath(TreeNode node, ArrayList<Integer> path, int value) {
if (node == null) {
return path;
} else {
if (node.data == value) {
path.add(value);
return path;
} else {
path.add(node.data);
printPath(node.left, path, value);
printPath(node.right, path, value);
}
}
return path;
}
Currently I am getting output as [20, 8, 4, 12, 22] When I should be only getting [20,8,12].
I added the Binary search tree in the picture, path is an empty ArrayList, and value is 12
Assuming you want only the shortest path from the root-Node to the given value, you must compare the value with the current node's data and then decide whether to go left or right (and not go both directions).
public static ArrayList<Integer> printPath(TreeNode node, ArrayList<Integer> path, int value) {
if (node == null)
return path;
path.add(node.data);
int cmp = Integer.compare(value, node.data);
if (cmp < 0) // value is smaller, so go left
printPath(node.left, path, value);
else if (cmp > 0) // value is larger, so go right
printPath(node.right, path, value);
else /* if (cmp == 0) */
return path; // value found
return path;
}
This should give [20, 8, 12] for the proposed tree when calling:
printPath(root, new ArrayList<Integer>(), 12);
public static ArrayList<Integer> printPath(TreeNode node, ArrayList<Integer> path, int value) {
if (node == null) {
return path;
}
path.add(node.data);
if (node.data < value) {
printPath(node.right, path, value);
} else if(node.data>value){
printPath(node.left, path, value);
}
return path;
}
A testable Solution with some sample data:
import java.util.ArrayList;
import java.util.List;
class TreeNode
{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int x) { data = x; }
public TreeNode(TreeNode node)
{
this.data = node.data;
this.left = node.left;
this.right = node.right;
}
public void add(TreeNode node)
{
if(data > node.data)
{
if(left == null)
left = node;
else
left.add(node);
}
if(data < node.data)
if(right == null)
right = node;
else
right.add(node);
}
}
class Tree
{
TreeNode root;
public Tree(TreeNode node)
{
this.root = node;
}
public Tree()
{
this.root = null;
}
public void add(TreeNode node)
{
if(root == null)
{
root = node;
}
if(root.data > node.data){
if(root.left == null)
root.left = node;
else
root.left.add(node);
}
if(root.data < node.data)
{
if(root.right == null)
root.right = node;
else
root.right.add(node);
}
}
public void addInt(int value){
add(new TreeNode(value));
}
public void postorder(TreeNode n)
{
if (n != null)
{
postorder(n.left);
postorder(n.right);
System.out.print(n.data + " ");
}
}
public void inorder(TreeNode n)
{
if (n != null)
{
inorder(n.left);
System.out.print(n.data + " ");
inorder(n.right);
}
}
}
public class TreeTest
{
public static void main(String[] args)
{
Tree tree = new Tree();
tree.add(new TreeNode(3));
tree.add(new TreeNode(2));
tree.add(new TreeNode(5));
tree.add(new TreeNode(9));
tree.add(new TreeNode(4));
tree.add(new TreeNode(1));
tree.add(new TreeNode(10));
tree.addInt(11);
ArrayList<Integer> mylist = printPath(tree.root, new ArrayList<Integer>(),10);
System.out.println("the path is "+mylist);
tree.inorder(tree.root);
System.out.println("");
tree.postorder(tree.root);
}
public static ArrayList<Integer> printPath(TreeNode node, ArrayList<Integer> path, int value) {
if (node == null) {
return path;
}
if (node.data == value) {
path.add(value);
return path;
}
if(node.data > value){
path.add(node.data);
printPath(node.left, path, value);
}
if(node.data < value) {
path.add(node.data);
printPath(node.right,path, value);
}
return path;
}
}