I was doing an assignment in which I'm supposed to create a binary tree and define given functions from its abstract superclass (AbstractBinaryTree.java).
While working on a function called getNumbers() which is basically going to traverse through the whole tree whilst adding values from each node to an array list which it returns. There seems to be a null pointer in one of my if statements.
AbstractBinaryTree.java
import java.util.ArrayList;
public abstract class AbstractBinaryTree
{
protected Node root;
protected int sizeOfTree;
public AbstractBinaryTree()
{
root = null;
sizeOfTree = 0;
}
public int size(){ return sizeOfTree; }
/** compute the depth of a node */
public abstract int depth(Node node);
/** Check if a number is in the tree or not */
public abstract boolean find(Integer i);
/** Create a list of all the numbers in the tree. */
/* If a number appears N times in the tree then this */
/* number should appear N times in the returned list */
public abstract ArrayList<Integer> getNumbers();
/** Adds a leaf to the tree with number specifed by input. */
public abstract void addLeaf(Integer i);
/** Removes "some" leaf from the tree. */
/* If the tree is empty should return null */
public abstract Node removeLeaf();
// these methods are only needed if you wish
// use the TreeGUI visualization program
public int getheight(Node n){
if( n == null) return 0;
return 1 + Math.max(
getheight(n.getLeft()) , getheight(n.getRight())
);
}
public int height(){ return getheight(root); }
}
Node.java File.
public class Node{
protected Integer data;
protected Node left;
protected Node right;
public Node(Integer data)
{
this.data = data;
this.left = this.right = null;
}
public Node(Integer data, Node left, Node right){
this.data = data;
this.left = left;
this.right = right;
}
public Integer getData(){ return this.data; }
public Node getLeft(){ return this.left; }
public Node getRight(){ return this.right; }
public void setLeft(Node left){ this.left = left; }
public void setRight(Node right){ this.right = right; }
public void setData(Integer data){ this.data = data; }
}
BinaryTree.java
import java.util.ArrayList;
import java.util.*;
// Student Name: Adrian Robertson
// Student Number: 101020295
//
// References: Collier, R. "Lectures Notes for COMP1406C- Introduction to Computer Science II" [PDF documents]. Retrieved from cuLearn: https://www.carleton.ca/culearn/(Winter2016).//
// References: http://codereview.stackexchange.com/questions/13255/deleting-a-node-from-a-binary-search-tree
// http://www.algolist.net/Data_structures/Binary_search_tree/Removal
// http://www.geeksforgeeks.org/inorder-tree-traversal- without-recursion-and-without-stack/
public class BinaryTree extends AbstractBinaryTree
{
protected Node root = new Node(12);
public static BinaryTree create()
{
BinaryTree tempTree = new BinaryTree();
//creating all the nodes
Node temp10 = new Node(10);
Node temp40 = new Node(40);
Node temp30 = new Node(30);
Node temp29 = new Node(29);
Node temp51 = new Node(51);
Node temp61 = new Node(61);
Node temp72 = new Node(72);
Node temp31 = new Node(31);
Node temp32 = new Node(32);
Node temp42 = new Node(42);
Node temp34 = new Node(34);
Node temp2 = new Node(2);
Node temp61x2 = new Node(61);
Node temp66 = new Node(66);
Node temp3 = new Node(3);
Node temp73 = new Node(73);
Node temp74 = new Node(74);
Node temp5 = new Node(5);
//setting up the tree
if (tempTree.root.getData() == null)
{
tempTree.root.setData(12);
tempTree.root.setLeft(temp10);
tempTree.root.setRight(temp40);
}
temp10.setLeft(temp30);
temp30.setRight(temp29);
temp29.setRight(temp51);
temp51.setLeft(temp61);
temp51.setRight(temp72);
temp40.setLeft(temp31);
temp31.setLeft(temp42);
temp31.setRight(temp34);
temp34.setLeft(temp61x2);
temp61x2.setLeft(temp66);
temp61x2.setRight(temp73);
temp40.setRight(temp32);
temp32.setRight(temp2);
temp2.setLeft(temp3);
temp3.setRight(temp74);
temp74.setLeft(temp5);
return tempTree;
}
public int depth(Node node)
{
Node current = this.root;
int counter = 1;
while(node != current)
{
if (node.getData() > current.getData())
current = current.getRight();
if (node.getData() < current.getData())
current = current.getLeft();
}
return counter;
}
public boolean find(Integer i)
{
boolean found = false;
Node current = this.root;
if (i == current.getData())
found = true;
while (i != current.getData())
{
if (i > current.getData())
current = current.getRight();
if (i < current.getData())
current = current.getLeft();
if (i == current.getData())
found = true;
}
return found;
}
public ArrayList<Integer> getNumbers()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Node current = this.root;
Node Pre = new Node(null);
while (current.getData() != null )
{
if (current.getLeft().getData() == null)
{
temp.add(current.getData());
current = current.getRight();
}
else
{
/* Find the inorder predecessor of current */
Pre = current.getLeft();
while(Pre.getRight() != null && Pre.getRight() != current)
Pre = Pre.getRight();
/* Make current as right child of its inorder predecessor */
if (Pre.getRight() == null)
{
Pre.setRight(current);
current = current.getLeft();
}
/* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */
else
{
Pre.setRight(null);
temp.add(current.getData());
current = current.getRight();
}/* End of if condition Pre.right == NULL */
}/* End of if condition current.left == NULL*/
}/*End of while */
Collections.sort(temp);
return temp;
}
public void addLeaf(Integer i)
{
insert(this.root, i);
}
public static void insert(Node node, int value) //insert a node Based on provided argument where node is the root of tree
{
if (node == null)
{
Node first = new Node(value);
node = first;
}
else if (value < node.getData())
{
if (node.left != null)
{
insert(node.left, value);
}
else
{
System.out.println(" > Inserted " + value + " to left of node " + node.getData());
Node newNode = new Node(value);
node.left = newNode;
}
}
else if (value > node.getData())
{
if (node.right != null)
{
insert(node.right, value);
}
else
{
System.out.println(" > Inserted " + value + " to right of node " + node.getData());
Node newNode = new Node(value);
node.right = newNode;
}
}
}
public Node removeLeaf()
{
Node tempA = new Node(61); //create a new node with that value
deleteNodeBST(this.root, 61); //delete the node containing that leaf value
return tempA; //return the copy of that node
}
//delete given node with given value
public boolean deleteNodeBST(Node node, int data) {
ArrayList<Integer> temp = this.getNumbers();
if (node == null) {
return false;
}
if (node.getData() == data) {
if ((node.getLeft() == null) && (node.getRight() == null)) {
// leaf node
node = null;
return true;
}
if ((node.getLeft() != null) && (node.getRight() != null)) {
// node with two children
node.setData(temp.get(0));
return true;
}
// either left child or right child
if (node.getLeft() != null) {
this.root.setLeft(node.getLeft());
node = null;
return true;
}
if (node.getRight() != null) {
this.root.setRight(node.getRight());
node = null;
return true;
}
}
this.root = node;
if (node.getData() > data) {
return deleteNodeBST(node.getLeft(), data);
} else {
return deleteNodeBST(node.getRight(), data);
}
}
public static void main(String args[])
{
BinaryTree myTree = new BinaryTree();
myTree.create();
System.out.println(myTree.getNumbers());
}
}
The create function creates a binary tree and returns that binary tree. This is the predefined binary tree that I was supposed to create according to assignment guidelines. I understand that the tree values are not organised properly as they would be in a proper binary tree. Is that was causes the null pointer during traversal? Cause the traversal is taylored to work for a proper Binary tree.
In class BinaryTree, you initialize the left and right of your root node only if the haven't data. But the root node is create with data...
You should invert the condition in :
//setting up the tree
if (tempTree.root.getData() == null)
And add a test in getNumbers() :
if (current.getLeft() == null || current.getLeft().getData() == null)
In the BinaryTree class, getNumbers() method and while loop. Maybe your problem is here:
if (current.getLeft().getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
When you call current.getLeft(), it will return null when the left Node is null. And then, you call getData() it will throw a NullPointerException. If you're not sure that it always not null check it before you call any methods of it. Example you can change the if statement to:
if (current.getLeft() != null && current.getLeft().getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
Or:
Node left = current.getLeft();
if (left == null) {
//TODO something here
} else if (left.getData() == null) {
temp.add(current.getData());
current = current.getRight();
}
Please update your getNumbers - method accordingly,
You need to put right checks before work with reference type.
public ArrayList<Integer> getNumbers()
{
ArrayList<Integer> temp = new ArrayList<Integer>();
Node current = this.root;
Node Pre = new Node(null);
while (current != null && current.getData() != null ) // Fix here... Add : current != null
{
if (current.getLeft() != null && current.getLeft().getData() == null) // Fix here... Add : current.getLeft() != null
{
temp.add(current.getData());
current = current.getRight();
}
else
{
/* Find the inorder predecessor of current */
Pre = current.getLeft();
while(Pre != null && Pre.getRight() != null && Pre.getRight() != current) // Fix here... Add : Pre != null
Pre = Pre.getRight();
/* Make current as right child of its inorder predecessor */
if (Pre != null && Pre.getRight() == null) // Fix here... Add : Pre != null
{
Pre.setRight(current);
current = current.getLeft();
}
/* Revert the changes made in if part to restore the original tree i.e., fix the right child of predecssor */
else
{
if(Pre != null){ // Fix here... Add : Pre != null
Pre.setRight(null);
}
temp.add(current.getData());
current = current.getRight();
}/* End of if condition Pre.right == NULL */
}/* End of if condition current.left == NULL*/
}/*End of while */
Collections.sort(temp);
return temp;
}
Related
I'm trying to build a binary tree recursively for an AI I'm developing.
I try to build a tree but everything comes back null. The language is Java and I'm using Eclipse. Also, I'm on a Mac if that means anything. The tree should be returned as a binary tree with nodes instantiated but without any content.
public class DecisionTree {
//build a generic, empty, tree
//building binary
Root r = new Root();
public void build() //ok
{
Node lhs = new Node();
Node rhs = new Node();
lhs = new Node();
rhs = new Node();
r.lhs = lhs;
r.rhs = rhs;
lhs.parent = r;
rhs.parent = r;
builtRecursion(lhs, 1);
builtRecursion(rhs, 1);
outputTree();
int ctr = 1; //levels of tree
}
public int builtRecursion(Node n, int ctr)
{
Node lhs = new Node();
Node rhs = new Node();
ctr++;
System.out.println("built recursion ctr is " + ctr);
if (ctr > 10)
{
//leaf node
Behaviors behavior = new Behaviors();
Node node = behavior;
n.b = behavior;
return 0;
}
n.lhs = lhs;
n.rhs = rhs;
lhs.parent = n;
rhs.parent = n;
builtRecursion(lhs, ctr);
builtRecursion(rhs, ctr);
return ctr;
}
public void outputTree()
{
if (r != null)
{
System.out.println("Root");
}
outputTreeRecursive(r);
}
public void outputTreeRecursive(Node n)
{
if (n.lhs != null)
{
System.out.println("------------------");
System.out.println("LHS");
outputTreeRecursive(n.lhs);
}
else { System.out.println("LHS is null");}
if (n.rhs != null)
{
System.out.println("-----------------");
System.out.println("RHS");
outputTreeRecursive(n.rhs);
}
else { System.out.println("RHS is null");}
System.out.println("-----------------");
}
}
ROOT CLASSS
package FLINCH;
public class Root extends Node {
Node lhs = new Node();
Node rhs = new Node();
}
NODE CLASS
package FLINCH;
import java.util.ArrayList;
import java.util.LinkedList;
public class Node {
Node lhs = null;
Node rhs = null;
Node parent = null;
Decider d = new Decider(this);
Behaviors b = null;
public LinkedList getSuccessors()
{
LinkedList list = new LinkedList();
list.add(lhs);
list.add(rhs);
return list;
}
}
OUTPUT
GetAction Running
Iterating through open list
Size of open list is 1
Peeked openLIst size is 1
Peeking throguh open list
Popping Open List
LHS is null
RHS is null
Number of children is 2
Children equals 2
Decider childrens loop
Child node is null
Iterating through children
Exception in thread "main" java.lang.NullPointerException
at FLINCH.A_Star_Search.search3(A_Star_Search.java:81)
at FLINCH.Soldier.search_behavior(Soldier.java:28)
at FLINCH.Main.getAction(Main.java:54)
at tests.GameVisualSimulationTest.main(GameVisualSimulationTest.java:52)
I hope this helps...
I have a piece of code which you can use for BinaryTree
public class BinarySearchTree {
public static Node root;
public BinarySearchTree(){
this.root = null;
}
public void insert(int id){
Node newNode = new Node(id);
if(root==null){
root = newNode;
return;
}
Node current = root;
Node parent = null;
while(true){
parent = current;
if(id < current.data){
current = current.left;
if(current==null){
parent.left = newNode;
return;
}
}else{
current = current.right;
if(current==null){
parent.right = newNode;
return;
}
}
}
}
public boolean find(int id){
Node current = root;
while(current!=null){
if(current.data==id){
return true;
}else if(current.data > id){
current = current.left;
}else{
current = current.right;
}
}
return false;
}
public boolean delete(int id){
Node parent = root;
Node current = root;
boolean isLeftChild = false;
while(current.data!=id){
parent = current;
if(current.data > id){
isLeftChild = true;
current = current.left;
}else{
isLeftChild = false;
current = current.right;
}
if(current ==null){
return false;
}
}
//if i am here that means we have found the node
//Case 1: if node to be deleted has no children
if(current.left==null && current.right==null){
if(current==root){
root = null;
}
if(isLeftChild ==true){
parent.left = null;
}else{
parent.right = null;
}
}
//Case 2 : if node to be deleted has only one child
else if(current.right==null){
if(current==root){
root = current.left;
}else if(isLeftChild){
parent.left = current.left;
}else{
parent.right = current.left;
}
}
else if(current.left==null){
if(current==root){
root = current.right;
}else if(isLeftChild){
parent.left = current.right;
}else{
parent.right = current.right;
}
}else if(current.left!=null && current.right!=null){
//now we have found the minimum element in the right sub tree
Node successor = getSuccessor(current);
if(current==root){
root = successor;
}else if(isLeftChild){
parent.left = successor;
}else{
parent.right = successor;
}
successor.left = current.left;
}
return true;
}
public Node getSuccessor(Node deleleNode){
Node successsor =null;
Node successsorParent =null;
Node current = deleleNode.right;
while(current!=null){
successsorParent = successsor;
successsor = current;
current = current.left;
}
//check if successor has the right child, it cannot have left child for sure
// if it does have the right child, add it to the left of successorParent.
// successsorParent
if(successsor!=deleleNode.right){
successsorParent.left = successsor.right;
successsor.right = deleleNode.right;
}
return successsor;
}
public void display(Node root){
if(root!=null){
display(root.left);
System.out.print(" " + root.data);
display(root.right);
}
}
public static void printInOrder(Node root){
if(root == null){
return;
}
printInOrder(root.left);
System.out.print(root.data+" ");
printInOrder(root.right);
}
public static void printPreOrder(Node root){
if(root == null){
return;
}
System.out.print(root.data+" ");
printPreOrder(root.left);
printPreOrder(root.right);
}
public static void printPostOrder(Node root){
if(root == null){
return;
}
printPostOrder(root.left);
printPostOrder(root.right);
System.out.print(root.data+" ");
}
public static void main(String arg[]){
BinarySearchTree b = new BinarySearchTree();
b.insert(3);b.insert(8);
b.insert(1);b.insert(4);b.insert(6);b.insert(2);b.insert(10);b.insert(9);
b.insert(20);b.insert(25);b.insert(15);b.insert(16);
System.out.println("Original Tree : ");
b.display(b.root);
System.out.println("");
System.out.println("Check whether Node with value 4 exists : " + b.find(4));
System.out.println("Delete Node with no children (2) : " + b.delete(2));
b.display(root);
System.out.println("\n Delete Node with one child (4) : " + b.delete(4));
b.display(root);
System.out.println("\n Delete Node with Two children (10) : " + b.delete(10));
b.display(root);
System.out.println();
System.out.println("********* Printing In Order *********");
printInOrder(root);
System.out.println();
System.out.println("********* Printing Pre Order *********");
printPreOrder(root);
System.out.println();
System.out.println("********* Printing Post Order *********");
printPostOrder(root);
}
}
class Node{
int data;
Node left;
Node right;
public Node(int data){
this.data = data;
left = null;
right = null;
}
}
when you call your buildRecursion with ctr = 1, you probably mean you want to build a tree with just one extra level and from your comment where you expect to build a leaf node, the condition needs to be modified. in your case the condition should be:
if (ctr == 1)
I made some changes to your function for better output:
public void builtRecursion(Node n, int ctr)
{
System.out.println("built recursion ctr is " + ctr);
if (ctr == 1)
{
//leaf node
Behaviors behavior = new Behaviors();
n.b = behavior;
return;
}
Node lhs = new Node();
Node rhs = new Node();
n.lhs = lhs;
n.rhs = rhs;
lhs.parent = n;
rhs.parent = n;
builtRecursion(lhs, ctr--);
builtRecursion(rhs, ctr--);
}
About the problem regarding I try to build a tree but everything comes back null, well in your outputTree and outputRecursion you don't print anything instead of "-----", "LHS", "RHS" and in case you reach where there is no left or right node you will print "LHS/RHS is null" but you should know that with a leaf node this is an accepted behavior so when you reach the leaf nodes you should print their values instead. However you can change the outputTreeRecursive to the following:
public void outputTreeRecursive(Node n)
{
if (n.lhs != null)
{
System.out.println("------------------");
System.out.println("LHS");
outputTreeRecursive(n.lhs);
}
else {
System.out.println("LHS is null");
if(n.b != null)
System.out.println("Leaf node");
}
if (n.rhs != null)
{
System.out.println("-----------------");
System.out.println("RHS");
outputTreeRecursive(n.rhs);
}
else {
System.out.println("RHS is null");
if(n.b != null)
System.out.println("Leaf node");
}
System.out.println("-----------------");
}
now probably you get better idea about your tree
Been working on this for while with no luck. Hopefully someone can point in the right direction.
Code:
public class BST {
public BTNode<Integer> root;
int nonLeafCount = 0;
int depthCount = 0;
public BST() {
root = null;
}
class BTNode<T> {
T data;
BTNode<T> left, right;
BTNode(T o) {
data = o;
left = right = null;
}
public String toString() {
return String.valueOf(data);
}
}
}
The easy way to traverse a tree without recursive calls is to use a stack. Push the root on the stack, then enter a loop that - so long as the stack is not empty - pops a node from the stack and pushes the non-null children of that node. It's pretty obvious that this will eventually push every node onto the stack exactly once and pop it exactly once. Now all you need to do is count the popped nodes that have at least one child. Putting this together,
public int nonleaves() {
int nonLeafCount = 0;
BTNode<Integer> [] stack = new BTNode[2];
int p = 0;
stack[p++] = root; // push root
while (p != 0) {
BTNode<Integer> node = stack[--p]; // pop
if (node.left != null || node.right != null) ++nonLeafCount;
if (p + 1 >= stack.length) stack = Arrays.copyOf(stack, 2 * stack.length);
if (node.right != null) stack[p++] = node.right; // push right
if (node.left != null) stack[p++] = node.left; // push left
}
return nonLeafCount;
}
Note that in accordance with your description, I used a simple Java array for a stack, growing it by a factor of 2 whenever it fills up. Integer p is the stack pointer.
Also, this code assumes the root is non-null. If the root can be null, add a check at the start and return 0 in that case.
NB it's possible to traverse without even a stack by several methods, although at the cost of changing the tree during traversal. (It's back in its original shape when the traversal is complete.) The nicest IMO is Morris's algorithm, but all of them are considerably more complicated than the stack. Since it seems you're a new programmer, figure out the stack method first.
Edit
To find max depth:
public int maxDepth() {
int max = 0;
Pair<Integer> [] stack = new Pair[2];
int p = 0;
stack[p++] = new Pair(root, 1);
while (p != 0) {
Pair<Integer> pair = stack[--p];
if (pair.depth > max) max = pair.depth;
if (p + 1 >= stack.length) stack = Arrays.copyOf(stack, 2 * stack.length);
if (pair.node.right != null)
stack[p++] = new Pair(pair.node.right, 1 + pair.depth);
if (pair.node.left != null)
stack[p++] = new Pair(pair.node.left, 1 + pair.depth);
}
return max;
}
private static class Pair<T> {
BTNode<T> node;
int depth;
Pair(BTNode<T> node, int depth) {
this.node = node;
this.depth = depth;
}
}
Finally, I'd be remiss if I didn't point out that we can do some algebra on the algorithm to eliminate some tiny inefficiencies. You'll note that after the left child is pushed onto the stack, it is certain to be popped in the next loop iteration. The root push/pop is similar. We might as well set node directly. Also, there are some redundant comparisons. The details are too much for this note, but here is a reworked non-leaf counter (untested but ought to work fine):
public int nonleaves() {
int nonLeafCount = 0;
BTNode<Integer>[] stack = new BTNode[1];
int p = 0;
BTNode<Integer> node = root;
for (;;) {
if (node.left == null) {
if (node.right == null) {
if (p == 0) break;
node = stack[--p];
} else { // node.right != null
++nonLeafCount;
node = node.right;
}
} else { // node.left != null
++nonLeafCount;
if (node.right != null) {
if (p >= stack.length) {
stack = Arrays.copyOf(stack, 2 * stack.length);
}
stack[p++] = node.right;
}
node = node.left;
}
}
return nonLeafCount;
}
You can see that to eek out a tiny bit of efficiency we lose a lot of simplicity. This is almost always a bad bargain. I recommend against it.
A possible solution:
public class BST<T> {
public BTNode<T> root;
int depthCount = 0;
public BST() {
root = null;
}
public int nonleaves() { // Method must be declared like this. No
// parameters.
BTNode<T> current = root;
BTNode<T> previous = null;
int nonLeafCount = 0;
while (current != null) {
if (previous == current.parent) { // this includes when parent is
// null, i.e. current is the
// root.
previous = current;
if (current.left != null) {
nonLeafCount++;
current = current.left;
} else if (current.right != null) {
nonLeafCount++;
current = current.right;
} else {
current = current.parent;
}
} else if (previous == current.left) {
previous = current;
if (current.right != null) {
current = current.right;
} else {
current = current.parent;
}
} else {
// previous==current.right
previous = current;
current = current.parent;
}
}
return nonLeafCount;
}
private static class BTNode<T> {
BTNode<T> left, right, parent;
/* ... */
}
}
Using stacks:
public class BST2<T> {
public BTNode<T> root;
int depthCount = 0;
public BST2() {
root = null;
}
public int nonleaves() { // Method must be declared like this. No
// parameters.
BTNode<T> current = root;
BTNode<T> previous = null;
int nonLeafCount = 0;
MyStack myStack = new MyStack(); // New empty stack
while (current != null) {
if (previous == myStack.top()) { // this includes when stack is
// empty, i.e. current is the
// root.
myStack.push(current);
previous = current;
if (current.left != null) {
nonLeafCount++;
current = current.left;
} else if (current.right != null) {
nonLeafCount++;
current = current.right;
} else {
myStack.pop();
current = myStack.top();
}
} else if (previous == current.left) {
previous = current;
if (current.right != null) {
current = current.right;
} else {
myStack.pop();
current = myStack.top();
}
} else {
// previous==current.right
previous = current;
myStack.pop();
current = myStack.top();
}
}
return nonLeafCount;
}
private static class BTNode<T> {
BTNode<T> left, right;
/* ... */
}
}
hi i build this code for BST:
public class BinarySearchTreeCode {
private class BSTNode {
public Object data;
public BSTNode left;
public BSTNode right;
BSTNode(Object newdata) {
data = newdata;
left = null;
right = null;
}
BSTNode(Object data, BSTNode left, BSTNode right){
this.data = data;
this.left = left;
this.right = right;
}
public String toString(){
return "data: "+data+" ";
}
}
// tree root
private BSTNode root;
public BinarySearchTreeCode(){
root = null;
}
public BinarySearchTreeCode(BSTNode n){
root = n;
}
public BinarySearchTreeCode(BinarySearchTreeCode bst){// copy constructor
this.root = clone(bst.root);
}
BSTNode clone(final BSTNode source){
if (source == null) return null;
else
return new BSTNode(source.data, clone(source.left), clone(source.right));
}
// compare two objects (integer type)
private static int compare(Object o1, Object o2) {
int ans = 0;
int n1 = (Integer)o1;
int n2 = (Integer)o2;
if(n1>n2) ans = 1;
else if(n1<n2) ans = -1;
return ans;
}
// insert element to the tree
public void insertRecurs(Object elem) {
root = insertRecurs(root, elem);
}
BSTNode insertRecurs(BSTNode node, Object elem) {
if (node == null) {
return new BSTNode(elem);
}
if (compare(elem, node.data) < 0) {
node.left = insertRecurs(node.left, elem);
return node;
}
else{
node.right = insertRecurs(node.right, elem);
return node;
}
}
// search for element elem
public boolean find(Object elem) {
return find(root,elem);
}
boolean find(BSTNode tree, Object elem) {
if (tree == null)
return false;
if (compare(elem, tree.data) == 0)
return true;
if (compare(elem, tree.data) < 0)
return find(tree.left, elem);
else
return find(tree.right, elem);
}
// print all tree nodes
public void print() {
print(" ",root);
System.out.println();
}
void print(String s,BSTNode tree) {//Inorder
if (tree != null) {
print(s+"L ,",tree.left);
System.out.println(tree.data+" : "+s);
print(s+"R ,",tree.right);
}
}
///////////////////////////
public void remove(Object elem) {
root = remove(root, elem);
}
public static BSTNode remove(BSTNode node, Object n){
if(node != null){
if(compare(n,node.data) > 0){
node.right = remove(node.right,n);
}
else if(compare(n,node.data) < 0){
node.left = remove(node.left,n);
}
else{//the node that should be deleted is found
if(node.left == null && node.right == null){
node = null;
}
else if(node.left != null && node.right == null){//the node has only one child (left)
node = node.left;
}
else if(node.right != null && node.left == null){//the node has only one child (right)
node = node.right;
}
else{//node "tree" has two children
if(node.right.left == null){// his right node has only one child (right)
node.right.left = node.left;
node = node.right;
}
else{// remove the smallest element
BSTNode q, p = node.right;
while(p.left.left != null)
p = p.left;
q = p.left;
p.left = q.right;
node.data = q.data;
}
}
}
}
return node;
}
public void insertLoop(Object elem) {
BSTNode newNode = new BSTNode(elem);
if (root == null){
root = newNode;
}
else{
BSTNode n = root;
boolean flag = true;
while (flag){
if (compare(elem,n.data) > 0){
if (n.right != null) n = n.right;
else{
n.right = newNode;
flag = false;;
}
}
else{
if (n.left != null) n = n.left;
else{
n.left = newNode;
flag = false;;
}
}
}
}
}
public boolean isEmpty(){
return this.root == null;
}
//end of the code
the question is
how i build a function that give the max object in the BNT like this
public Object maximum(){
}
any Suggestions?
thank for yours help.
The maximum object in a Binary Search tree is the rightmost node. You can get it as follows :
1) Start from root node
2) Check if node.right is empty
3) If yes then node is the maximum object. terminate the search.
4) if not then move to rightmost nde (node = node.right) and repeat step 2.
Sample Code :
public BSTNode findMaxNode()
{
Node temp = root;
Node max = null;
while(temp != null)
{
max = temp;
temp = temp.right
}
return max;
}
I've been trying to create a integer binary search tree with Java and for some reason, I've been going wrong with adding new nodes to the tree.
Here is the NODE class.
class NODE
{
NODE left = null, right = null;
int info;
public NODE(int x)
{
info = x;
}
}
and here's the BST(Binary Seatch Tree) class with the insert() method.
class BST
{
NODE tree = null;
public void insert(int x)
{
NODE node = new NODE(x);
NODE temp = tree;
while(true)
{
if(temp == null)
{
temp = node;
break;
}
else if(temp.info > x) temp = temp.left;
else temp = temp.right;
}
}
//other methods present here
}
For reasons that I could not figure out, the insert() method is going wrong.
The object tree carries null in it even after the insert() method is called.
Can you find something spotty in the code?
Thanks!
Use a recursive insert method in the NODE class (instead of utilizing an infinite loop as you did):
public void insert(int x) {
if(x < this.info) {
if(this.left == null)
this.left = new NODE(x);
else
this.left.insert(x);
}
else {
if(this.right == null)
this.right = new NODE(x);
else
this.right.insert(x);
}
}
And your BST class would have the following insert method (simply calls the other insert method):
public void insert(int x) {
if(tree == null)
tree = new NODE(x);
else
tree.insert(x);
}
The main insert method is in the NODE class because it must recursively call itself on nodes within the tree.
Of course tree remains null - you don't assign anything to this field.
After temp = tree; and temp = node; only temp is changed, not tree.
The insert() method should insert the child of a node into the tree, calling an already declared Node as a parameter. e.g.:
//Returns true/false depending on whether the insert is successful
public boolean insert(int x, Node node, boolean leftChild) {
if (node == null) return false;
Node child = new Node(x);
if (leftChild) {
if (node.left != null) return false;
node.left = child;
} else {
if (node.right != null) return false;
node.right = child;
}
return true;
}
I am having some problems printing an inOrder traversal of my binary tree. Even after inserting many items into the tree it's only printing 3 items.
public class BinaryTree {
private TreeNode root;
private int size;
public BinaryTree(){
this.size = 0;
}
public boolean insert(TreeNode node){
if( root == null)
root = node;
else{
TreeNode parent = null;
TreeNode current = root;
while( current != null){
if( node.getData().getValue().compareTo(current.getData().getValue()) <0){
parent = current;
current = current.getLeft();
}
else if( node.getData().getValue().compareTo(current.getData().getValue()) >0){
parent = current;
current = current.getRight();
}
else
return false;
if(node.getData().getValue().compareTo(parent.getData().getValue()) < 0)
parent.setLeft(node);
else
parent.setRight(node);
}
}
size++;
return true;
}
/**
*
*/
public void inOrder(){
inOrder(root);
}
private void inOrder(TreeNode root){
if( root.getLeft() !=null)
this.inOrder(root.getLeft());
System.out.println(root.getData().getValue());
if( root.getRight() != null)
this.inOrder(root.getRight());
}
}
It seems that you are not traversing the tree properly upon insertion, to find the right place for the new node. Right now you are always inserting at one child of the root, because the insertion code is inside the while loop - it should be after it:
public boolean insert(TreeNode node){
if( root == null)
root = node;
else{
TreeNode parent = null;
TreeNode current = root;
while( current != null){
if( node.getData().getValue().compareTo(current.getData().getValue()) <0){
parent = current;
current = current.getLeft();
}
else if( node.getData().getValue().compareTo(current.getData().getValue()) >0){
parent = current;
current = current.getRight();
}
else
return false;
}
if(node.getData().getValue().compareTo(parent.getData().getValue()) < 0)
parent.setLeft(node);
else
parent.setRight(node);
}
size++;
return true;
}
You insert method has a problem. It finds the right parent node to attach the new element to, but on the way it messes up the whole tree. You should move the insertion code out of the while loop:
public boolean insert(TreeNode node){
if( root == null)
root = node;
else{
TreeNode parent = null;
TreeNode current = root;
while( current != null){
if( node.getData().getValue().compareTo(current.getData().getValue()) <0){
parent = current;
current = current.getLeft();
}
else if( node.getData().getValue().compareTo(current.getData().getValue()) >0){
parent = current;
current = current.getRight();
}
else
return false;
}
if(node.getData().getValue().compareTo(parent.getData().getValue()) < 0)
parent.setLeft(node);
else
parent.setRight(node);
}
size++;
return true;
}
}
hey fellows here is one simple one.. try this out.. it works for me well...
public void levelOrderTraversal(Node root){
Queue<Node> queue = new ArrayDeque<Node>();
if(root == null) {
return;
}
Node tempNode = root;
while(tempNode != null) {
System.out.print(tempNode.data + " ");
if(tempNode.left != null) queue.add(tempNode.left);
if(tempNode.right != null) queue.add(tempNode.right);
tempNode = queue.poll();
}
}