Printing Java Binary search tree - java

How to print out a binary search tree in java? I have written the code to insert to the tree but without being able to print the tree i am insure if the elements are adding. I will post my code below.
public class TreeNode {
TreeNode left;
TreeNode right;
TreeNode root;
int data;
public TreeNode(int d) {
data = d;
left = right = null;
root = null;
}
public synchronized void insert(int d) {
if (root == null){
root = new TreeNode( d );
}
if (d < data) {
if (left == null) {
left = new TreeNode(d);
} else {
left.insert(d);
}
} else if (d > data) {
if (right == null) {
right = new TreeNode(d);
} else {
right.insert(d);
}
}
}
public TreeNode treeSearch(TreeNode root, int target) {
if (root != null) {
if (target < root.data) {
root = treeSearch(root.left, target);
} else if (target > root.data) {
root = treeSearch(root.right, target);
}
}
return root;
}
}

You may use following method:
void printTree(TreeNode node, String prefix)
{
if(node == null) return;
System.out.println(prefix + " + " + node.data);
printTree(node.left , prefix + " ");
printTree(node.right , prefix + " ");
}
Initial call should be printTree( root,""); from where you want to print the tree. Here root is reference of root node.
UPDATED:
You can see this code working here

you can print the tree data like this.
public void printTree(TreeNode root) {
if (root == null) return;
System.out.println(root.data);
printTree(root.left);
printTree(root.right);
}

private void print(PrintWriter out) {
print(root, out, "");
}
private void print(TreeNode subtree, PrintWriter out, String indent) {
if (subtree != null) {
print(subtree.left, out, indent + "--");
out.printf("%s %s%n", indent, subtree.data);
print(subtree.right, out, indent + "--");
}
}

Infix order: Left - root - right
public String printInfix(TreeNode root) {//prints all the words in the tree in infix order
if(root==null) {
return "";
}
return printAll(root.left+" "+root.data+" "+printAll(root.right);
}

Related

How to print binary search tree in nice diagram?

I have to implement binary search tree with method that prints nice diagram with connections like this:
For now I managed to print this:
However I'm struggling to make it better :/
Do you have any hints how to fix that?
It's my code of instance implementing it:
public interface PrintableTree {
class Node {
int data;
Node left, right;
Node(int data) {
this.data = data;
this.left = null;
this.right = null;
}
}
class Trunk {
Trunk prev;
String str;
Trunk(Trunk prev, String str) {
this.prev = prev;
this.str = str;
}
}
Node insert_Recursive(Node root, int key);
void add(int i);
String prettyPrint();
static PrintableTree getInstance() {
return new PrintableTree() {
String stringOfTree = "";
static final int COUNT = 2;
Node root;
#Override
public void add(int i) {
root = insert_Recursive(root, i);
}
#Override
public Node insert_Recursive(Node root, int key) {
if (root == null) {
root = new Node(key);
return root;
}
if (key < root.data)
root.left = insert_Recursive(root.left, key);
else if (key > root.data)
root.right = insert_Recursive(root.right, key);
return root;
}
#Override
public String prettyPrint() {
printTree(root, null, false);
return "";
}
public void showTrunks(Trunk p) {
if (p == null) {
return;
}
showTrunks(p.prev);
System.out.print(p.str);
}
public void printTree(Node root, Trunk prev, boolean isLeft) {
if (root == null) {
return;
}
String prev_str = " ";
Trunk trunk = new Trunk(prev, prev_str);
printTree(root.left, trunk, true);
if (prev == null) {
trunk.str = "";
} else if (isLeft) {
trunk.str = "┌";
prev_str = " │";
} else {
trunk.str = "└";
prev.str = prev_str;
}
showTrunks(trunk);
System.out.println(" " + root.data);
if (prev != null) {
prev.str = prev_str;
}
trunk.str = " │";
printTree(root.right, trunk, false);
}
};
}
}
You could use these functions. They return a string, so it is up to the caller to print it.
I also find it nicer when the right subtree is printed upwards, and the left subtree downwards. That way, the tree is just rotated 90° from how it is usually depicted -- with the root at the top.
Here is the relevant code:
public String pretty() {
return pretty(root, "", 1);
}
private String pretty(Node root, String prefix, int dir) {
if (root == null) {
return "";
}
String space = " ".repeat(("" + root.data).length());
return pretty(root.right, prefix + "│ ".charAt(dir) + space, 2)
+ prefix + "└ ┌".charAt(dir) + root.data
+ " ┘┐┤".charAt((root.left != null ? 2 : 0)
+ (root.right != null ? 1 : 0)) + "\n"
+ pretty(root.left, prefix + " │".charAt(dir) + space, 0);
}

Getting nth item of a BST

I am trying to return the data held by the nth item of a BST, I'm trying to do an inorder traversal with a counter, and when the counter is larger than n, return the current node. My current code seems to always return the first item, and I can't see where my logic is wrong. I only wrote the nth and inOrder methods, the rest were provided. I think I'm incrementing my counter too often, is that the cause or am I doing something else wrong. I'll post the main method I'm testing with below as well.
import java.util.NoSuchElementException;
public class BST {
private BTNode<Integer> root;
public BST() {
root = null;
}
public boolean insert(Integer i) {
BTNode<Integer> parent = root, child = root;
boolean goneLeft = false;
while (child != null && i.compareTo(child.data) != 0) {
parent = child;
if (i.compareTo(child.data) < 0) {
child = child.left;
goneLeft = true;
} else {
child = child.right;
goneLeft = false;
}
}
if (child != null)
return false; // number already present
else {
BTNode<Integer> leaf = new BTNode<Integer>(i);
if (parent == null) // tree was empty
root = leaf;
else if (goneLeft)
parent.left = leaf;
else
parent.right = leaf;
return true;
}
}
public int greater(int n) {
if (root == null) {
return 0;
}
else {
return n;
}
}
int c = 0;
public int nth(int n) throws NoSuchElementException {
BTNode<Integer> node = null;
if (root == null) {
throw new NoSuchElementException("Element " + n + " not found in tree");
}
else {
if (root != null){
node = inOrder(root, n);
}
}
return node.data;
}
public BTNode inOrder(BTNode<Integer> node, int n) {
c++;
while (c <= n) {
if (node.left != null) {
inOrder(node.left, n);
}
c++;
if (node.right != null) {
inOrder(node.right, n);
}
}
return node;
}
}
class BTNode<T> {
T data;
BTNode<T> left, right;
BTNode(T o) {
data = o;
left = right = null;
}
}
public class bstTest {
public static void main(String[] args) {
BST tree = new BST();
tree.insert(2);
tree.insert(5);
tree.insert(7);
tree.insert(4);
System.out.println(tree.nth(2));
}
}
An invariant you should consider is that when n = sizeOfLeftSubtree + 1, then return that node. If n is less, then go left. If n is greater, then go right and reduce n by sizeOfLeftSubtree+1. Note that I map n=1 to the first element (the leftmost element).
You could trivially calculate the size of a subtree recursively, or you can store the size at every root (every node is a root of a subtree) modifying you insert method (save in a stack/queue all nodes visited and if a new node is added just increment all sizes by 1).
If the size is stored the complexity will be O(log n). If not if could become O(n^2).
public int nth(int n) throws NoSuchElementException {
if( sizeOfTree(this.root) < n || n < 1)
throw new NoSuchElementException("Element " + n + " not found in tree");
BTNode<Integer> root = this.root;
boolean found = false;
do{
int sizeOfLeftSubtree = sizeOfTree(root.left);
if( sizeOfLeftSubtree + 1 == n ){
found = true;
}else if( n < sizeOfLeftSubtree+1 ){
root = root.left;
}else if( sizeOfLeftSubtree+1 < n ){
root = root.right;
n -= sizeOfLeftSubtree+1;
}
}while( !found );
return root.data;
}
public int sizeOfTree(BTNode<Integer> root){
if( root == null )
return 0;
else
return sizeOfTree(root.left) + 1 + sizeOfTree(root.right);
}
You don't change node in the inOrder method.
public BTNode inOrder(BTNode<Integer> node, int n) {
c++;
while (c <= n) {
if (node.left != null) {
// **** Add this - or something.
node = inOrder(node.left, n);
}
c++;
if (node.right != null) {
// **** Add this - or something.
node = inOrder(node.right, n);
}
}
return node;
}
Not suggesting this is the bug you are trying to fix but it is certainly a problem with the code.

Binary Search Tree - print out number of leaves

I have a program that is a binary search tree, the method searches for a specific word. I'm having two problems.
First is I would like to print the true or false from this method (basically making a system.out that says if the word was found), I'm assuming I would do it in main but I'm not sure how to do that.
The second problem is that I also need to print out how many leaves are in the tree, I was going to use a counter of some sort in the method but I didn't work.
My method is below but I also included it inside the class to help clear up any confusion.
Any help would be greatly appreciated.
public boolean check(BSTNode t,String key)
{
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
Whole class:
public class BST
{
BSTNode root;
BST() {
root = null;
}
public void add2Tree(String st)
{
BSTNode newNode = new BSTNode(st);
if (this.root == null) {
root = newNode;
} else {
root = addInOrder(root, newNode);
}
}
// private BSTNode insert2(BSTNode root, BSTNode newNode)
// {
// if (root == null)
// root = newNode;
// else {
// System.out.println(root.word + " " + newNode.word);
// if (root.word.compareTo(newNode.word) > 0)
// {
// root.left = (insert2(root.lTree, newNode));
// System.out.println(" left ");
// } else
// {
// root.rTree = (insert2(root.rTree, newNode));
// System.out.println(" right ");
// }
// }
// return root;
// }
public BSTNode addInOrder(BSTNode focus, BSTNode newNode) {
int comparevalue = 0;
if (focus == null) {
focus = newNode;
}
if (focus != null) {
comparevalue = newNode.word.compareTo(focus.word);
}
if (comparevalue < 0) {
focus.left = addInOrder(focus.left, newNode);
} else if (comparevalue > 0) {
focus.right = addInOrder(focus.right, newNode);
}
return (focus);
}
public void ioprint() {
System.out.println(" start inorder");
if (root == null)
System.out.println(" Null");
printinorder(root);
}
public void printinorder(BSTNode t) {
if (t != null) {
printinorder(t.left);
System.out.println(t.word);
printinorder(t.right);
}
}
public boolean check(BSTNode t,String key)
{
if (t == null) return false;
if (t.word.equals(key)) return true;
if (check(t.left,key)) return true;
if (check(t.right,key)) return true;
return false;
}
public BSTNode getroot(){
return root;
}
}
How to print true/false:
Create another class, call it Solution, Test or whatever you like.
Add a main method to it.
Populate your BST.
Call System.out.println(check(bstRoot, key)).
You can check this link to find out how to count the number of nodes in BST, it's pretty straightforward:
Counting the nodes in a binary search tree
private int countNodes(BSTNode current) {
// if it's null, it doesn't exist, return 0
if (current == null) return 0;
// count myself + my left child + my right child
return 1 + nodes(current.left) + nodes(current.right);
}

How can print all nodes that are greater than specific node in tree?

I make this code to search about key then print all nodes greater than this key
public boolean search(int data) {
return search(root, data);
}
private boolean search(BSTnode p, int data) {
if (p == null)
return false;
else {
// if the data we are searching for is found at p (at the current root)
if (data == p.getData())
return true;
else if (data < p.getData())
return search(p.getLeft(), data);
else
return search(p.getRight(), data);
}
}
and I try make this code to print all nodes greater than the key
public void printAllNodeGreaterMyFoundNode(int data) {
printAllNodeGreaterMyFoundNode(root, data);
}
private void printAllNodeGreaterMyFoundNode(BSTnode p, int data){
if(data<p.getData())
System.out.print(p.getData());
finally this my void main
System.out.print("> What value do you want to search for: ");
value = input.nextInt();
if (myTree.search(value)){
System.out.println("> " + value + " was found in the tree and the values greater than "+value+"are:");
myTree.printAllNodeGreaterMyFoundNode(value);
Could anyone can help me please?
Method 1: When each BSTNode has access to its parent
public void printGreater(BSTNode root, int value) {
BSTNode data = search(root, value);
BSTNode succ;
if (data != null) {
System.out.println("> " + value + " was found in the tree and the values greater than " + value + "are:");
while (data != null) {
succ = successor(data);
if (succ != null) {
System.out.println(succ.data);
}
data = succ;
}
}
}
private BSTNode search(BSTNode p, int data) {
if (p == null)
return null;
else {
// if the data we are searching for is found at p (at the current
// root)
if (data == p.data)
return p;
else if (data < p.data)
return search(p.left, data);
else
return search(p.right, data);
}
}
In the main method
System.out.print("> What value do you want to search for: ");
value = input.nextInt();
printGreater(bstRootNode, value);
Method 2: If you don't have access to the parent node in the BSTNode class
public void printGreaterWithoutParent(BSTNode root, int value) {
BSTNode data = search(root, value);
if (data != null) {
System.out
.println("> " + value + " was found in the tree and the values greater than " + value + "are:");
greaterNodes(root, data);
}
}
private void greaterNodes(BSTNode n, BSTNode k) {
if (n == null)
return;
greaterNodes(n.left, k);
if (n.data > k.data) {
System.out.println(n.data);
}
greaterNodes(n.right, k);
}
In the main method
System.out.print("> What value do you want to search for: ");
value = input.nextInt();
printGreaterWithoutParent(bstRootNode, value);
You can do this by traversing the whole tree, and using a simple if comparator statement :
private void printAllNodeGreaterMyFoundNode(BSTnode p, int data){
if(p == null){
//do nothing reached the end
return;
}
else{
if(p.getData() >= data){
System.out.println(p.getData());
}
printAllNodeGreaterMyFoundNode(p.getLeft(), data);
printAllNodeGreaterMyFoundNode(p.getRight(), data);
}
}
Once you find the node in BS tree, then you can just traverse on the right subtree, rooted at the searched node.

binary search tree deletion method [duplicate]

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

Categories

Resources