Illegal start of expression with <> [duplicate] - java

This question already has answers here:
What is the point of the diamond operator (<>) in Java?
(7 answers)
Closed 5 years ago.
I keep on getting this whenever I run my code with -Xlint:
Tester.java:11: error: illegal start of type
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
^
Tester.java:11: error: illegal start of expression
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
^
Tester.java:11: error: illegal start of expression
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
the code is meant to make a double threaded binary search treee. I'd like to actually test my code but I keep on getting these errors
my code:
DoubleThreadedBST
Code is selfexplanitory(also has comments)
public class DoubleThreadedBST<T extends Comparable<? super T>>
{
private DTNode<T> root; // the root node of the tree
public static boolean dLeft;
public static boolean dRight;
/*
TODO: You must complete each of the methods in this class to create
your own double threaded BST. You may add any additional methods
or data fields which you might need to accomplish your task. You
must NOT change the signatures of any methods given to you with this
class.
*/
public DoubleThreadedBST()
{
root = null;
}
public DoubleThreadedBST(DoubleThreadedBST<T> other)
{
root = other.getRoot();
}
public DoubleThreadedBST<T> clone()
{
DoubleThreadedBST<T> other = new DoubleThreadedBST<T>();
other.setRoot(this.root);
return other;
}
public DTNode<T> getRoot()
{
return root;
}
public void setRoot(DTNode<T> r){
root = r;
}
public boolean insert(T element){
DTNode<T> newNode = new DTNode<T>(element);
if(root != null){
if(contains(element) == false){
if(root.hasLeftT() != true){
root.setLeft(newNode);
root.setHasLeftT(true);
root.setLeftBit(1);
newNode.setRight(root);
newNode.setHasRightT(true);
newNode.setRightBit(0);
return true;
}else if (root.hasRightT() != true){
root.setRight(newNode);
root.setHasRightT(true);
root.setRightBit(1);
newNode.setLeft(root);
newNode.setHasLeftT(true);
newNode.setLeftBit(0);
return true;
}else{
DTNode<T> trav = root.getLeft();
while(true){
if(trav.getData().compareTo(newNode.getData()) == 1){
if(trav.getLeftBit() == 0){
newNode.setLeft (trav.getLeft());
trav.setLeft(newNode);
newNode.setLeftBit (trav.getLeftBit());
trav.setLeftBit(1);
newNode.setRight(trav);
break;
}else{
trav = trav.getLeft();
}
}else{
if(trav.getRightBit() == 0){
newNode.setRight(trav.getRight());
trav.setRight(newNode);
newNode.setRightBit(trav.getRightBit());
trav.setRightBit(1);
newNode.setLeft(trav);
break;
}else{
trav = trav.getRight();
}
}
}
}
}else{
return false;
}
}else{
root = newNode;
root.setLeft(null);
root.setRight(null);
root.setHasLeftT(false);
root.setHasRightT(false);
return true;
}
/*
The element passed in as a parameter should be
inserted into this tree. Duplicates are not allowed.
Left and right threads in the corresponding branch
must be updated accordingly, as necessary.
If the insert was successfull, the method should
return true. If the operation was unsuccessfull,
the method should return false.
NB: Do not throw an exception.
*/
return true;
}
/*
public boolean delete(T element){
if(contains(element){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
}
while(trav != null){
if(trav.getRight().getData() == element){
DTNode<T> temp = trav.getRight();
trav.setRight(keeper.getRight());
while (temp 1= null){
}
}
if(trav.hasRightT()){
trav = trav.getRight();
}else{
trav = trav.getLeft();
}
}
}
*/
/*
The element passed in as a parameter should be
deleted from this tree. If the delete was successfull,
the method should return true. If the operation was
unsuccessfull, the method should return false. Eg, if
the requested element is not found, return false.
You have to implement the mirror case of delete by merging
as discussed in the textbook. That is, for a deleted node,
its right child should replace it in the tree and not its
left child as in the textbook examples. Relevant left and
right threads must be updated accordingly.
NB: Do not throw an exception.
return false;
}
*/
public boolean contains(T element){
if(root != null){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
}
while(trav != null){
if(trav.getData() == element){
return true;
}
if(trav.hasRightT()){
trav = trav.getRight();
}else{
trav = trav.getLeft();
}
}
}
return false;
}
public String inorderAscending(){
String tree = "";
if(root != null){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
}
while(trav != null){
tree += trav.getData();
if(trav.getRight() != null){
tree += ",";
}
if(trav.hasRightT()){
trav = trav.getRight();
}else{
trav = trav.getLeft();
}
}
}
/*
This method must return a string representation
of the elements in the tree inorder, left to right.
This function must not be recursive. Instead, right
threads must be utilised to perform a depth-first
inorder traversal.
If the tree looks like:
B
/ \
A D
/ \
C E
Then the following string must be returned:
A,B,C,D,E
Note that there are no spaces in the string, and
the elements are comma-separated.
*/
return tree;
}
public String inorderDescending(){
String tree = "";
if(root != null){
DTNode<T> trav = root;
while (trav.getRight()!= null){
trav = trav.getRight();
}
while(trav != null){
tree += trav.getData();
if(trav.getLeft() != null){
tree += ",";
}
if(trav.hasLeftT()){
trav = trav.getLeft();
}else{
trav = trav.getRight();
}
}
}
/*
This method must return a string representation
of the elements in the tree inorder, right to left.
This function must not be recursive. Instead, left
threads must be utilised to perform a depth-first
inorder traversal.
If the tree looks like:
B
/ \
A D
/ \
C E
Then the following string must be returned:
E,D,C,B,A
Note that there are no spaces in the string, and the elements are comma-separated.
*/
return tree;
}
public int countRightThreads(){
int count = 0;
if(root != null){
DTNode<T> trav = root;
while (trav.getRight() != null){
trav = trav.getRight();
count ++;
}
while(trav != null){
if(trav.hasLeftT()){
trav = trav.getLeft();
}else{
count++;
trav = trav.getRight();
}
}
}
/*
This method should return the total number of right threads
in the tree.
*/
return count;
}
public int countLeftThreads(){
int count = 0;
if(root != null){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
count++;
}
while(trav != null){
if(trav.hasLeftT()){
trav = trav.getLeft();
count ++;
}else{
trav = trav.getRight();
}
}
}
/*
This method should return the total number of left threads
in the tree.
*/
return count;
}
public int getNumberOfNodes()
{
int count = 0;
if(root != null){
DTNode<T> trav = root;
while (trav.getLeft()!= null){
trav = trav.getLeft();
count++;
}
while(trav != null){
if(trav.hasLeftT()){
trav = trav.getLeft();
count ++;
}else{
trav = trav.getRight();
count++;
}
}
}
/*
This method should count and return the number of nodes
currently in the tree.
*/
return count;
}
public int getHeight()
{
/*
This method should return the height of the tree. The height
of an empty tree is 0; the height of a tree with nothing but
the root is 1.
*/
return 0;
}
}
Tester
Just for testing
public class Tester
{
public static void main(String[] args) throws Exception
{
/*
TODO: Write your code to test your implementation here.
This file will be overwritten for marking purposes
*/
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
BST.insert(1);
BST.insert(2);
BST.insert(3);
BST.insert(5);
BST.insert(4);
System.out.println(BST.inorderAscending());
System.out.println(BST.inorderDescending());
}
}
DTNode
Has a left and a right while my ...Bits show whether they left and right are pointing to an in order parent or a child node.
public class DTNode<T extends Comparable<? super T>>
{
/*
TODO: You must implement a node class which would be appropriate to use with your trees.
Methods and variables can be added.
Names of the given variables must not be altered.
*/
//setters
public DTNode(){
}
public DTNode(T elem){
data = elem;
}
public void setLeft(DTNode<T> n){
left = n;
}
public void setRight(DTNode<T> n){
right = n;
}
public void setData(T elem){
data = elem;
}
public void setHasLeftT(boolean t){
hasLeftThread = t;
}
public void setHasRightT(boolean t){
hasRightThread = t;
}
public void setLeftBit(int b){
leftBit = b;
}
public void setRightBit(int b){
rightBit= b;
}
//getters
public DTNode<T> getLeft(){
return left;
}
public DTNode<T> getRight(){
return right;
}
public T getData(){
return data;
}
public boolean hasLeftT(){
return hasLeftThread;
}
public boolean hasRightT(){
return hasRightThread;
}
public int getLeftBit(){
return leftBit;
}
public int getRightBit(){
return rightBit;
}
protected T data;
protected DTNode<T> left, right; // left child and right child
protected boolean hasLeftThread, hasRightThread; // flags that indicate whether the left and the right pointers are threads
protected int leftBit, rightBit;
}

Reference declaration doesnt accept diamond operator, which means you have to send a generic argument. Repleace this:
DoubleThreadedBST<> BST = new DoubleThreadedBST()<>;
with:
DoubleThreadedBST<Integer> BST = new DoubleThreadedBST<>();

Related

Summing elements of binary tree in Java

I'm trying to sum the elements of a binary tree with a recursive and an iterative method. While the recursive one works finde, the iterative gives me an exception.
import java.util.Queue;
public class BinTree {
public BinNode root;
public boolean insertNode(BinNode bn) {
BinNode child=null, parent=null;
// Knoten suchen, nach welchem eingefuegt wird
child = root;
while( child != null) {
parent = child;
if (bn.element == child.element) return false;
else if (bn.element < child.element) child = child.left;
else child = child.right;
}
// Baum leer?
if (parent==null) root = bn;
// Einfuegen nach parent, links
else if (bn.element < parent.element) parent.left = bn;
// Einfuegen nach parent, rechts
else parent.right = bn;
return true;
}
public BinNode findNode(int value) {
BinNode n = root;
while (n != null) {
if (value == n.element) { return n; }
else if (value < n.element) { n = n.left; }
else { n = n.right; }
}
return null;
}
public String toString() {
return root.toString();
}
//Max des Gesamtbaumes
public int max(){
if(root==null){
return 0;
}
else {
return root.max();
}
}
//(Iterativ)
public int max2(){
//The line that throws out the exception
Queue q = new LinkedList();
int sum = 0;
if(root!=null){
q.add(root);
}
while(!q.isEmpty()){
BinNode node = (BinNode) q.remove();
if(node.left == null && node.right == null){
sum = sum + node.element;
}
else{
if(node.left != null){
q.add(node.left);
}
}
if(node.right != null){
q.add(node.right);
}
}
return sum;
}
}
The Queue q = new LinkedList(); in the max2-Method is giving me the Exception:
Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - incompatible types: javaapplication34.LinkedList cannot be converted to java.util.Queue
Could anyone help here? Give me a kickstart or a little explanation? I'm very unsure what's the issue in detail.
I didn't add every class here, since most of them are common. But if needed I'll add them.
It appears that you have defined a class called LinkedList in the same package, and it doesn't implement Queue.
If you want to use a java.util.LinkedList, you should either import or use the entire qualified name.
We don't know the implementation of you special LinkedList class (only that it does not implement the java.lang.Queue interface), but it may work already if you just say:
LinkedList q = new LinkedList();
(I assume that it is an assignment and that you have to use this special LinkedList for the task)

Infinite loop when replacing a node in an unsorted tree

I'm doing a homework assignment in Java where I have to create an unsorted binary tree with a String as the data value. I then have to write a function that replaces a Node and any duplicate Nodes that match an old description with a new object that contains a new description.
Here is the code that I am working with, including the test case that causes an infinite loop:
public class Node {
private String desc;
private Node leftNode = null;
private Node rightNode = null;
private int height;
public Node(String desc) {
this.desc = desc;
height = 0; // assumes that a leaf node has a height of 0
}
public String getDesc() {
return desc;
}
public Node getLeftNode() {
return leftNode;
}
public Node getRightNode() {
return rightNode;
}
public void setLeftNode(Node node) {
++height;
leftNode = node;
}
public void setRightNode(Node node) {
++height;
rightNode = node;
}
public int getHeight() {
return height;
}
public int addNode(Node node) {
if(leftNode == null) {
setLeftNode(node);
return 1;
}
if(rightNode == null) {
setRightNode(node);
return 1;
}
if(leftNode.getHeight() <= rightNode.getHeight()) {
leftNode.addNode(node);
++height;
} else {
rightNode.addNode(node);
++height;
}
return 0;
}
public static void displayTree(Node root) {
if(root != null) {
displayTree(root.getLeftNode());
System.out.println(root.getDesc());
displayTree(root.getRightNode());
}
}
public static Node findNode(Node current, String desc) {
Node result = null;
if(current == null) {
return null;
}
if(current.getDesc().equals(desc)) {
return current;
}
if(current.getLeftNode() != null) {
result = findNode(current.getLeftNode(), desc);
}
if(result == null) {
result = findNode(current.getRightNode(), desc);
}
return result;
}
public static void replaceNode(Node root, String oldDesc, String newDesc) {
if(oldDesc == null || newDesc == null) {
System.out.println("Invalid string entered");
return;
}
boolean replacedAllNodes = false;
while(replacedAllNodes == false) {
Node replace = findNode(root, oldDesc);
if(replace == null) { // No more nodes to replace
replacedAllNodes = true;
return;
}
replace = new Node(newDesc);
root.addNode(replace);
}
return;
}
public static void main(String[] args) {
Node root = new Node("test1");
Node test_2 = new Node("test2");
Node test_3 = new Node("test3");
Node test_4 = new Node("test4");
Node test_5 = new Node("test5");
Node test_6 = new Node("test6");
root.addNode(test_2);
root.addNode(test_3);
root.addNode(test_4);
root.addNode(test_5);
root.addNode(test_6);
displayTree(root);
replaceNode(root, "test4", "hey");
System.out.println("-------");
displayTree(root);
}
}
After testing the findNode method, and seeing that it returns the correct object, I realized that the infinite loop was being caused by my replaceNode method. I'm just not really sure how it is causing it.
I got it to work with one case by removing the while loop, but obviously that won't work for duplicates, so I'm wondering how I could remove the node with oldDesc and replace it with a new object that contains newDesc when there could be multiple objects with matching oldDesc data.
you are never changing root or oldDesc in your while loop
while(replacedAllNodes == false) {
Node replace = findNode(root, oldDesc);
if(replace == null) { // No more nodes to replace
replacedAllNodes = true;
return;
}
replace = new Node(newDesc);
root.addNode(replace);
}
If you watch
public static Node findNode(Node current, String desc) {
Node result = null;
if(current == null) {
return null;
}
if(current.getDesc().equals(desc)) {
return current;
}
if(current.getLeftNode() != null) {
result = findNode(current.getLeftNode(), desc);
}
if(result == null) {
result = findNode(current.getRightNode(), desc);
}
return result;
}
If the if(current.getDesc().equals(desc)) condition matches, replace will always be root so you are stuck in your while loop
Update:
If you dont necessarily have to replace the whole node, you could just update the description for your node at the end of your while loop.
instead of
replace = new Node(newDesc);
root.addNode(replace);
do something like:
root.setDesc(newDesc);
(of course you would have to create a setDesc() method first)
If you have to replace the whole object, you have to go like this:
Instead of
replace = new Node(newDesc);
root.addNode(replace);
do something like this:
replace = new Node(newDesc);
replace.setLeftNode(root.getLeftNode);
replace.setRightNode(root.getRightNode);
Plus you have to link the node that pointed to root so it points to replace like one of the following examples (depends on which side your root was of course):
nodeThatPointedToRoot.setLeftNode(replace);
nodeThatPointedToRoot.setRightNode(replace);
well looking at your code, you are not replacing a node you are just adding a new node to the edge of the tree and the old node would still be there so the loop will go forever and you can add a temp variable with an auto increment feature and to indicate the level of the node you are reaching to replace and you'll find it's just doing it again and again, instead of doing all this process how about just replacing the description inside that node ?

Finding a node in a binary search tree in java?

I am trying to write a method that returns the depth of a target int in a binary search tree. Right now it works for some smaller trees, but not always. Does anyone see where I may be going wrong?
static int count=1;
public static int findDepth(TreeNode<Integer> root, int target)
// pre: 0 or more elements in the tree, integer to search for
// post: return depth of target if found, -1 otherwise
{
count++;
if (root!=null)
{
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
else
{findDepth(root.getLeft(), target);
count--;
findDepth(root.getRight(), target);
}
}
else if (root.getValue()==target)
return 1;
else
return -1;
}
return count;
}
There's a few things wrong.
It will never get into this case:
if (root.getValue()<target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
Also it will never get into this case:
else if (root.getValue()>target)
{
if (root.getValue()==target)
{System.out.println(count);
return count;}
The biggest issue is that you're keeping a global static count, and recursively going through both left and right paths.
First of all, for a BST, there is no need to go both left and right.
Second, it's better to pass the count through a parameter rather than keeping a global.
Rather than fix your code, I'll post this working example for you to use as a reference:
public class Main
{
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.add(20);
tree.add(10);
tree.add(30);
tree.add(15);
tree.add(25);
tree.add(5);
tree.add(35);
tree.add(1);
tree.add(6);
tree.add(14);
tree.add(16);
tree.add(24);
tree.add(26);
tree.add(34);
tree.add(36);
int level = tree.getLevel(6);
System.out.println(level);
}
}
public class TreeNode
{
int data;
TreeNode left;
TreeNode right;
public TreeNode(int d){
data = d;
left = null;
right = null;
}
}
public class BinaryTree
{
TreeNode root;
public BinaryTree(){
root = null;
}
public int getLevel(int val) {
if (root == null) return 0;
return getLevelHelper(root, val, 0);
}
public int getLevelHelper(TreeNode node, int val, int level){
int retVal = -1;
if (node.data == val){
return level;
}
if (val < node.data && node.left != null){
retVal = getLevelHelper(node.left, val, level + 1);
}
else if (val > node.data && node.right != null){
retVal = getLevelHelper(node.right, val, level + 1);
}
return retVal;
}
public boolean add(int newData){
if (root == null){
root = new TreeNode(newData);
return true;
}
else{
TreeNode curr = root;
while (true){
if (curr.data == newData){
return false;
}
else if (curr.data > newData){
if (curr.left == null){
curr.left = new TreeNode(newData);
return true;
}
else{
curr = curr.left;
}
}
else{
if (curr.right == null){
curr.right = new TreeNode(newData);
return true;
}
else{
curr = curr.right;
}
}
}
}
}
}

Remove method binary search tree

I am trying to implement a remove method for the BST structure that I have been working on. Here is the code with find, insert, and remove methods:
public class BST {
BSTNode root = new BSTNode("root");
public void insert(BSTNode root, String title){
if(root.title!=null){
if(title==root.title){
//return already in the catalog
}
else if(title.compareTo(root.title)<0){
if(root.leftChild==null){
root.leftChild = new BSTNode(title);
}
else{
insert(root.leftChild,title);
}
}
else if(title.compareTo(root.title)>0){
if(root.rightChild==null){
root.rightChild = new BSTNode(title);
}
else{
insert(root.rightChild,title);
}
}
}
}
public void find(BSTNode root, String title){
if(root!= null){
if(title==root.title){
//return(true);
}
else if(title.compareTo(root.title)<0){
find(root.leftChild, title);
}
else{
find(root.rightChild, title);
}
}
else{
//return false;
}
}
public void remove(BSTNode root, String title){
if(root==null){
return false;
}
if(title==root.title){
if(root.leftChild==null){
root = root.rightChild;
}
else if(root.rightChild==null){
root = root.leftChild;
}
else{
//code if 2 chlidren remove
}
}
else if(title.compareTo(root.title)<0){
remove(root.leftChild, title);
}
else{
remove(root.rightChild, title);
}
}
}
I was told that I could use the insert method to help me with the remove method, but I am just not seeing how I can grab the smallest/largest element, and then replace the one I am deleting with that value, then recursively delete the node that I took the replacement value, while still maintaining O(logn) complexity. Anyone have any ideas or blatant holes I missed, or anything else helpful as I bang my head about this issue?
EDIT:
I used the answers ideas to come up with this, which I believe will work but I'm getting an error that my methods (not just the remove) must return Strings, here is what the code looks like, I thought that's the return statements??
public String remove(BSTNode root, String title){
if(root==null){
return("empty root");
}
if(title==root.title){
if(root.leftChild==null){
if(root.rightChild==null){
root.title = null;
return(title+ "was removed");
}
else{
root = root.rightChild;
return(title+ "was removed");
}
}
else if(root.rightChild==null){
root = root.leftChild;
return(title+ "was removed");
}
else{
String minTitle = minTitle(root);
root.title = minTitle;
remove(root.leftChild,minTitle);
return(title+ "was removed");
}
}
else if(title.compareTo(root.title)<0){
remove(root.leftChild, title);
}
else{
remove(root.rightChild, title);
}
}
public void remove (String key, BSTNode pos)
{
if (pos == null) return;
if (key.compareTo(pos.key)<0)
remove (key, pos.leftChild);
else if (key.compareTo(pos.key)>0)
remove (key, pos.rightChild);
else {
if (pos.leftChild != null && pos.rightChild != null)
{
/* pos has two children */
BSTNode maxFromLeft = findMax (pos.leftChild); //need to make a findMax helper
//"Replacing " pos.key " with " maxFromLeft.key
pos.key = maxFromLeft.key;
remove (maxFromLeft.key, pos.leftChild);
}
else if(pos.leftChild != null) {
/* node pointed by pos has at most one child */
BSTNode trash = pos;
//"Promoting " pos.leftChild.key " to replace " pos.key
pos = pos.leftChild;
trash = null;
}
else if(pos.rightChild != null) {
/* node pointed by pos has at most one child */
BSTNode trash = pos;
/* "Promoting " pos.rightChild.key" to replace " pos.key */
pos = pos.rightChild;
trash = null;
}
else {
pos = null;
}
}
}
This is the remove for an unbalanced tree. I had the code in C++ so I have quickly translated. There may be some minor mistakes though. Does the tree you are coding have to be balanced? I also have the balanced remove if need be. I wasn't quite sure based on the wording of your question. Also make sure you add a private helper function for findMax()
void deleteTreeNode(int data){
root = deleteTreeNode(root ,data);
}
private TreeNode deleteTreeNode(TreeNode root, int data) {
TreeNode cur = root;
if(cur == null){
return cur;
}
if(cur.data > data){
cur.left = deleteTreeNode(cur.left, data);
}else if(cur.data < data){
cur.right = deleteTreeNode(cur.right, data);
}else{
if(cur.left == null && cur.right == null){
cur = null;
}else if(cur.right == null){
cur = cur.left;
}else if(cur.left == null){
cur = cur.right;
}else{
TreeNode temp = findMinFromRight(cur.right);
cur.data = temp.data;
cur.right = deleteTreeNode(cur.right, temp.data);
}
}
return cur;
}
private TreeNode findMinFromRight(TreeNode node) {
while(node.left != null){
node = node.left;
}
return node;
}
To compare objects in java use .equals() method instead of "==" operator
if(title==root.title)
^______see here
you need to use like this
if(title.equals(root.title))
or if you are interesed to ignore the case follow below code
if(title.equalsIgnoreCase(root.title))
private void deleteNode(Node temp, int n) {
if (temp == null)
return;
if (temp.number == n) {
if (temp.left == null || temp.right == null) {
Node current = temp.left == null ? temp.right : temp.left;
if (getParent(temp.number, root).left == temp)
getParent(temp.number, root).left = current;
else
getParent(temp.number, root).right = current;
} else {
Node successor = findMax(temp.left);
int data = successor.number;
deleteNode(temp.left, data);
temp.number = data;
}
} else if (temp.number > n) {
deleteNode(temp.left, n);
} else {
deleteNode(temp.right, n);
}
}
I know this is a very old question but anyways... The accepted answer's implementation is taken from c++, so the idea of pointers still exists which should be changed as there are no pointers in Java. So every time when you change the node to null or something else, that instance of the node is changed but not the original one This implementation is taken from one of the coursera course on algorithms.
public TreeNode deleteBSTNode(int value,TreeNode node)
{
if(node==null)
{
System.out.println("the value " + value + " is not found");
return null;
}
//delete
if(node.data>value) node.left = deleteBSTNode(value,node.left);
else if(node.data<value) node.right = deleteBSTNode(value,node.right);
else{
if(node.isLeaf())
return null;
if(node.right==null)
return node.left;
if(node.left==null)
return node.right;
TreeNode successor = findMax(node.left);
int data = successor.data;
deleteBSTNode(data, node.left);
node.data = data;
}
return node;
}
All the links between the nodes are pertained using the return value from the recursion.
For the Depth First Post-Order traversal and removal, use:
/*
*
* Remove uses
* depth-first Post-order traversal.
*
* The Depth First Post-order traversal follows:
* Left_Child -> Right-Child -> Node convention
*
* Partial Logic was implemented from this source:
* https://stackoverflow.com/questions/19870680/remove-method-binary-search-tree
* by: sanjay
*/
#SuppressWarnings("unchecked")
public BinarySearchTreeVertex<E> remove(BinarySearchTreeVertex<E> rootParameter, E eParameter) {
BinarySearchTreeVertex<E> deleteNode = rootParameter;
if ( deleteNode == null ) {
return deleteNode; }
if ( deleteNode.compareTo(eParameter) == 1 ) {
deleteNode.left_child = remove(deleteNode.left_child, eParameter); }
else if ( deleteNode.compareTo(eParameter) == -1 ) {
deleteNode.right_child = remove(deleteNode.right_child, eParameter); }
else {
if ( deleteNode.left_child == null && deleteNode.right_child == null ) {
deleteNode = null;
}
else if ( deleteNode.right_child == null ) {
deleteNode = deleteNode.left_child; }
else if ( deleteNode.left_child == null ) {
deleteNode = deleteNode.right_child; }
else {
BinarySearchTreeVertex<E> interNode = findMaxLeftBranch( deleteNode.left_child );
deleteNode.e = interNode.e;
deleteNode.left_child = remove(deleteNode.left_child, interNode.e);
}
} return deleteNode; } // End of remove(E e)
/*
* Checking right branch for the swap value
*/
#SuppressWarnings("rawtypes")
public BinarySearchTreeVertex findMaxLeftBranch( BinarySearchTreeVertex vertexParameter ) {
while (vertexParameter.right_child != null ) {
vertexParameter = vertexParameter.right_child; }
return vertexParameter; } // End of findMinRightBranch

implementing binary search tree insert

I'm trying to write code for a binary search tree, the first method I'm working on is the add (insert) method. The root seems to insert properly, but I'm getting null pointer exception when adding the second node. I'll indicate the exact problem spot in my code with comments.
If you can see how to fix the bugs, or let me know if my overall logic is flawed it would be incredibly helpful.-- I will mention that this is for school, so I'm not looking to make a really impressive model...most of my layout choices simply reflect the way we've been working in class. Also, method names were selected by the teacher and should stay the same. Feel free to edit the formatting, had a little trouble.
BINARY TREE CLASS
public class BinarySearchTree
{
private static Node root;
public BinarySearchTree()
{
root = null;
}
public static void Add (Node newNode)
{
Node k = root;
if (root == null)//-----------------IF TREE IS EMPTY -----------------
{
root = newNode;
}
else // -------TREE IS NOT EMPTY --------
{
if (newNode.value > k.value) //-------NEW NODE IS LARGER THAN ROOT---------
{
boolean searching = true;
while(searching) // SEARCH UNTIL K HAS A LARGER VALUE
{ //***CODE FAILS HERE****
if(k.value > newNode.value || k == null)
{
searching = false;
}
else {k = k.rightChild; }
}
if ( k == null) { k = newNode;}
else if (k.leftChild == null){ k.leftChild = newNode;}
else
{
Node temp = k.leftChild;
k.leftChild = newNode;
newNode = k.leftChild;
if(temp.value > newNode.value )
{
newNode.rightChild = temp;
}
else
{
newNode.leftChild = temp;
}
}
}
if (newNode.value < k.value) //-----IF NEW NODE IS SMALLER THAN ROOT---
{
boolean searching = true;
while(searching) // ----SEARCH UNTIL K HAS SMALLER VALUE
{// **** CODE WILL PROBABLY FAIL HERE TOO ***
if(k.value < newNode.value || k == null) {searching = false;}
else {k = k.leftChild;}
}
if ( k == null) { k = newNode;}
else if (k.rightChild == null){ k.rightChild = newNode;}
else
{
Node temp = k.rightChild;
k.rightChild = newNode;
newNode = k.rightChild;
if(temp.value > newNode.value )
{
newNode.rightChild = temp;
}
else
{
newNode.leftChild = temp;
}
}
}
}} // sorry having formatting issues
}
NODE CLASS
public class Node
{
int value;
Node leftChild;
Node rightChild;
public Node (int VALUE)
{
value = VALUE;
}
}
TEST APPLICATION
public class TestIT
{
public static void main(String[] args)
{
BinarySearchTree tree1 = new BinarySearchTree();
Node five = new Node(5);
Node six = new Node(6);
tree1.Add(five);
tree1.Add(six);
System.out.println("five value: " + five.value);
System.out.println("five right: " + five.rightChild.value);
}
}
The conditional statement is checked from left to right, so you need to check whether k is null before you check whether k.value > newNode.value because if k is null, then it doesn't have a value.

Categories