Binary Tree in Java - ******URGENT********
HI,
i want to represent a binary tree in java. is there any way of doing that.
thanx
sraphson
HI,
i want to represent a binary tree in java. is there
e any way of doing that.
thanx
sraphsonFirst, what is a binary tree? Do you know how the binary tree looks like on puesdo code? How about a representation in terms of numbers? What is a tree? What is binary? The reason I ask is, what do you know about programming?
Asking to represent a binary tree in java seems like a question who doesn't know how it looks like in the first please. Believe me, I am one of them. I am not at this level yet. If you are taking a class that is teaching binary trees and you don't know how it looks like, go back to your notes.
Sounds harsh, but it is better to hear it from a person that doesn't know either then a boss that hired you because Computer Science was what you degree said. Yet, you don't know how to program?
Telling you will not help you learn. I can show you tutorials of trees would be start on where to learn.
HOW TO USE TREES (oops this is too simple, but it is a good example)
http://java.sun.com/docs/books/tutorial/uiswing/components/tree.html
CS312 Data Structures and Analysis of Algorithms
(Here is a course about trees. Search and learn)
http://www.calstatela.edu/faculty/jmiller6/cs312-winter2003/index.htm
Similar Messages
-
Creating non binary trees in Java
Hi everybody actually i am used in creating binary trees in java,can u please tell me how do we create non binary -trees in java.
Hi,
Can u let us know the application area for Non binary tree.
S Rudra -
Hi guys i am used in creating binary trees ,tell me how do we create non binary trees in java.
public class Node {
private final Object payload;
private final Set<Node> children;
public Node(Object payload) {
this.payload = payload;
children = new HashSet<Node>();
// now add methods to add/remove children, a method to do something with the payload (say,
// a protected method that passes the payload to a method specified by some kind of interface),
// and methods to recurse over children.
}Actually rather than using Object probably should have generic-ized the class, but whatever. -
Hi there
Do you have any suggestions about how to implement trees or binary trees in Java?
As far as I know there are already some libraries for that, but I don't know how to use them. Was trying to get some implementation examples but I'm still very confused.
How can I use for example:
removeChild(Tree t)
addChild(Tree t)
isLeaf()
Thanks in advanceLulu wrote:
Hi there
I have several questions about binary trees
Let's see, I use TreeMap to create them with the following code:
TreeMap treeMap = new TreeMap<Integer, String>();
treeMap.put("first", "Fruit");
treeMap.put("second","Orange");
treeMap.put("third", "Banana");
treeMap.put("fourth", "Apple");You've defined the map to hold integer keys and strings as values, yet you're trying to add string keys and string values to it: that won't work.
If this is a map how do I define if the data should go to the left or to the right of certain node?That is all done for you. In a TreeMap (using the no-args constructor), you can only store objects that are comparable to each other (so, they must implement the Comparable interface!). So the dirty work of deciding if the entry should be stored, or traversed, into the left or right subtree of a node, is all done behind the scenes.
Also note that TreeMap is not backed up by a binary tree, or a binary search tree, but by a red-black tree. A red-black tree is a self balancing binary tree structure.
Should I have dynamical keys so that they increase automatically when adding new data?
According to a webpage I should use Comparator(), is that to find the data in the tree and retrieve the key?
ThanksI am not sure what it is you want. I am under the impression that you have to write a binary tree (or a binary search tree) for a course for school/university. Is that correct? If so, then I don't think you're permitted to use a TreeMap, but you'll have to write your own classes. -
Implementation of a parse tree in Java (Urgent)
How best can a parse tree be implemented in java, i have read some online information that suggest use of data structures, but i am still not clear on how to do it.
Well, you need a tree. A logical way to structure a tree is out of "node" objects. A node presumeably will hold some data, and may also have one or more subnodes.
So the root of your effort ought to go into designing the node - data it will hold, and getters and setters, and operations to walk the tree. -
Binary search tree in java using a 2-d array
Good day, i have been wrestling with this here question.
i think it does not get any harder than this. What i have done so far is shown at the bottom.
We want to use both Binary Search Tree and Single Linked lists data structures to store a text. Chaining
techniques are used to store the lines of the text in which a word appears. Each node of the binary search
tree contains four fields :
(i) Word
(ii) A pointer pointing to all the lines word appears in
(iii) A pointer pointing to the subtree(left) containing all the words that appears in the text and are
predecessors of word in lexicographic order.
(iv) A pointer pointing to the subtree(right) containing all the words that appears in the text and are
successors of word in lexicographic order.
Given the following incomplete Java classes BinSrchTreeWordNode, TreeText, you are asked to complete
three methods, InsertionBinSrchTree, CreateBinSrchTree and LinesWordInBinSrchTree. For
simplicity we assume that the text is stored in a 2D array, a row of the array represents a line of the text.
Each element in the single linked list is represented by a LineNode that contains a field Line which represents a line in which the word appears, a field next which contains the address of a LineNode representing the next line in which the word appears.
public class TreeText{
BinSrchTreeWordNode RootText = null;// pointer to the root of the tree
String TextID; // Text Identification
TreeText(String tID){TextID = tID;}
void CreateBinSrchTree (TEXT text){...}
void LinesWordInBinSrchTree(BinSrchTreeWordNode Node){...}
public static void main(String[] args)
TEXT univ = new TEXT(6,4);
univ.textcont[0][0] = "Ukzn"; univ.textcont[0][1] ="Uct";
univ.textcont[0][2] ="Wits";univ.textcont[0][3] ="Rhodes";
univ.textcont[1][0] = "stellenbosch";
univ.textcont[1][1] ="FreeState";
univ.textcont[1][2] ="Johannesburg";
univ.textcont[1][3] = "Pretoria" ;
univ.textcont[2][0] ="Zululand";univ.textcont[2][1] ="NorthWest";
univ.textcont[2][2] ="Limpopo";univ.textcont[2][3] ="Wsu";
univ.textcont[3][0] ="NorthWest";univ.textcont[3][1] ="Limpopo";
univ.textcont[3][2] ="Uct";univ.textcont[3][3] ="Ukzn";
univ.textcont[4][0] ="Mit";univ.textcont[4][1] ="Havard";
univ.textcont[4][2] ="Michigan";univ.textcont[4][3] ="Juissieu";
univ.textcont[5][0] ="Cut";univ.textcont[5][1] ="Nmmu";
univ.textcont[5][2] ="ManTech";univ.textcont[5][3] ="Oxford";
// create a binary search tree (universities)
// and insert words of text univ in it
TreeText universities = new TreeText("Universities");
universities.CreateBinSrchTree(univ);
// List words Universities trees with their lines of appearance
System.out.println();
System.out.println(universities.TextID);
System.out.println();
universities.LinesWordInBinSrchTree(universities.RootText);
public class BinSrchTreeWordNode {
BinSrchTreeWordNode LeftTree = null; // precedent words
String word;
LineNode NextLineNode = null; // next line in
// which word appears
BinSrchTreeWordNode RightTree = null; // following words
BinSrchTreeWordNode(String WordValue)
{word = WordValue;} // creates a new node
BinSrchTreeWordNode InsertionBinSrchTree
(String w, int line, BinSrchTreeWordNode bst)
public class LineNode{
int Line; // line in which the word appears
LineNode next = null;
public class TEXT{
int NBRLINES ; // number of lines
int NBRCOLS; // number of columns
String [][] textcont; // text content
TEXT(int nl, int nc){textcont = new String[nl][nc];}
The method InsertionBinSrchTree inserts a word (w) in the Binary search tree. The method Create-
BinSrchTree creates a binary search tree by repeated calls to InsertionBinSrchTree to insert elements
of text. The method LinesWordInBinSrchTree traverses the Binary search tree inorder and displays the
words with the lines in which each appears.
>>>>>>>>>>>>>>>>>>>>>>
//InsertionBinTree is of type BinSearchTreeWordNode
BinSrchTreeWordNode InsertionBinSrchTree(String w, int line, BinSrchTreeWordNode bst)
//First a check must be made to make sure that we are not trying to //insert a word into an empty tree. If tree is empty we just create a //new node.
If (bst == NULL)
System.out.println(Tree was empty)
For (int rows =0; rows <= 6; rows++)
For (int cols = 0; cols <= 4; cols++)
Textcont[i][j] = wWhat is the purpose of this thread? You are yet to ask a question... Such a waste of time...
For future reference use CODE TAGS when posting code in a thread.
But again have a think about how to convey a question to others instead of blabbering on about nothing.
i think it does not get any harder than this.What is so difficult to understand. Google an implementation of a binary tree using a single array. Then you can integrate this into the required 2-dimension array for your linked list implemented as an array in your 2-d array.
Mel -
Drawing Binary Diagrams/Trees in Java
I am needing some of ur expertise. I am requiring to represent a binary decision diagram using Java. The size of the binary decision diagram will vary (e.g. different number of nodes and edges) need some help or advice to find out as to how to do this in Java 2D? and how would it be possible to make the diagram editable (Move, resize).
Many thanksLulu wrote:
Hi there
I have several questions about binary trees
Let's see, I use TreeMap to create them with the following code:
TreeMap treeMap = new TreeMap<Integer, String>();
treeMap.put("first", "Fruit");
treeMap.put("second","Orange");
treeMap.put("third", "Banana");
treeMap.put("fourth", "Apple");You've defined the map to hold integer keys and strings as values, yet you're trying to add string keys and string values to it: that won't work.
If this is a map how do I define if the data should go to the left or to the right of certain node?That is all done for you. In a TreeMap (using the no-args constructor), you can only store objects that are comparable to each other (so, they must implement the Comparable interface!). So the dirty work of deciding if the entry should be stored, or traversed, into the left or right subtree of a node, is all done behind the scenes.
Also note that TreeMap is not backed up by a binary tree, or a binary search tree, but by a red-black tree. A red-black tree is a self balancing binary tree structure.
Should I have dynamical keys so that they increase automatically when adding new data?
According to a webpage I should use Comparator(), is that to find the data in the tree and retrieve the key?
ThanksI am not sure what it is you want. I am under the impression that you have to write a binary tree (or a binary search tree) for a course for school/university. Is that correct? If so, then I don't think you're permitted to use a TreeMap, but you'll have to write your own classes. -
Need Help with a String Binary Tree
Hi, I need the code to build a binary tree with string values as the nodes....i also need the code to insert, find, delete, print the nodes in the binarry tree
plssss... someone pls help me on this
here is my code now:
// TreeApp.java
// demonstrates binary tree
// to run this program: C>java TreeApp
import java.io.*; // for I/O
import java.util.*; // for Stack class
import java.lang.Integer; // for parseInt()
class Node
//public int iData; // data item (key)
public String iData;
public double dData; // data item
public Node leftChild; // this node's left child
public Node rightChild; // this node's right child
public void displayNode() // display ourself
System.out.print('{');
System.out.print(iData);
System.out.print(", ");
System.out.print(dData);
System.out.print("} ");
} // end class Node
class Tree
private Node root; // first node of tree
public Tree() // constructor
{ root = null; } // no nodes in tree yet
public Node find(int key) // find node with given key
{ // (assumes non-empty tree)
Node current = root; // start at root
while(current.iData != key) // while no match,
if(key < current.iData) // go left?
current = current.leftChild;
else // or go right?
current = current.rightChild;
if(current == null) // if no child,
return null; // didn't find it
return current; // found it
} // end find()
public Node recfind(int key, Node cur)
if (cur == null) return null;
else if (key < cur.iData) return(recfind(key, cur.leftChild));
else if (key > cur.iData) return (recfind(key, cur.rightChild));
else return(cur);
public Node find2(int key)
return recfind(key, root);
public void insert(int id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public void insert(String id, double dd)
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
if(root==null) // no node in root
root = newNode;
else // root occupied
Node current = root; // start at root
Node parent;
while(true) // (exits internally)
parent = current;
//if(id < current.iData) // go left?
if(id.compareTo(current.iData)>0)
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
parent.leftChild = newNode;
return;
} // end if go left
else // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
parent.rightChild = newNode;
return;
} // end else go right
} // end while
} // end else not root
} // end insert()
public Node betterinsert(int id, double dd)
// No duplicates allowed
Node return_val = null;
if(root==null) { // no node in root
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
root = newNode;
return_val = root;
else // root occupied
Node current = root; // start at root
Node parent;
while(current != null)
parent = current;
if(id < current.iData) // go left?
current = current.leftChild;
if(current == null) // if end of the line,
{ // insert on left
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.leftChild = newNode;
} // end if go left
else if (id > current.iData) // or go right?
current = current.rightChild;
if(current == null) // if end of the line
{ // insert on right
Node newNode = new Node(); // make new node
newNode.iData = id; // insert data
newNode.dData = dd;
return_val = newNode;
parent.rightChild = newNode;
} // end else go right
else current = null; // duplicate found
} // end while
} // end else not root
return return_val;
} // end insert()
public boolean delete(int key) // delete node with given key
if (root == null) return false;
Node current = root;
Node parent = root;
boolean isLeftChild = true;
while(current.iData != key) // search for node
parent = current;
if(key < current.iData) // go left?
isLeftChild = true;
current = current.leftChild;
else // or go right?
isLeftChild = false;
current = current.rightChild;
if(current == null)
return false; // didn't find it
} // end while
// found node to delete
// if no children, simply delete it
if(current.leftChild==null &&
current.rightChild==null)
if(current == root) // if root,
root = null; // tree is empty
else if(isLeftChild)
parent.leftChild = null; // disconnect
else // from parent
parent.rightChild = null;
// if no right child, replace with left subtree
else if(current.rightChild==null)
if(current == root)
root = current.leftChild;
else if(isLeftChild)
parent.leftChild = current.leftChild;
else
parent.rightChild = current.leftChild;
// if no left child, replace with right subtree
else if(current.leftChild==null)
if(current == root)
root = current.rightChild;
else if(isLeftChild)
parent.leftChild = current.rightChild;
else
parent.rightChild = current.rightChild;
else // two children, so replace with inorder successor
// get successor of node to delete (current)
Node successor = getSuccessor(current);
// connect parent of current to successor instead
if(current == root)
root = successor;
else if(isLeftChild)
parent.leftChild = successor;
else
parent.rightChild = successor;
// connect successor to current's left child
successor.leftChild = current.leftChild;
// successor.rightChild = current.rightChild; done in getSucessor
} // end else two children
return true;
} // end delete()
// returns node with next-highest value after delNode
// goes to right child, then right child's left descendents
private Node getSuccessor(Node delNode)
Node successorParent = delNode;
Node successor = delNode;
Node current = delNode.rightChild; // go to right child
while(current != null) // until no more
{ // left children,
successorParent = successor;
successor = current;
current = current.leftChild; // go to left child
// if successor not
if(successor != delNode.rightChild) // right child,
{ // make connections
successorParent.leftChild = successor.rightChild;
successor.rightChild = delNode.rightChild;
return successor;
public void traverse(int traverseType)
switch(traverseType)
case 1: System.out.print("\nPreorder traversal: ");
preOrder(root);
break;
case 2: System.out.print("\nInorder traversal: ");
inOrder(root);
break;
case 3: System.out.print("\nPostorder traversal: ");
postOrder(root);
break;
System.out.println();
private void preOrder(Node localRoot)
if(localRoot != null)
localRoot.displayNode();
preOrder(localRoot.leftChild);
preOrder(localRoot.rightChild);
private void inOrder(Node localRoot)
if(localRoot != null)
inOrder(localRoot.leftChild);
localRoot.displayNode();
inOrder(localRoot.rightChild);
private void postOrder(Node localRoot)
if(localRoot != null)
postOrder(localRoot.leftChild);
postOrder(localRoot.rightChild);
localRoot.displayNode();
public void displayTree()
Stack globalStack = new Stack();
globalStack.push(root);
int nBlanks = 32;
boolean isRowEmpty = false;
System.out.println(
while(isRowEmpty==false)
Stack localStack = new Stack();
isRowEmpty = true;
for(int j=0; j<nBlanks; j++)
System.out.print(' ');
while(globalStack.isEmpty()==false)
Node temp = (Node)globalStack.pop();
if(temp != null)
System.out.print(temp.iData);
localStack.push(temp.leftChild);
localStack.push(temp.rightChild);
if(temp.leftChild != null ||
temp.rightChild != null)
isRowEmpty = false;
else
System.out.print("--");
localStack.push(null);
localStack.push(null);
for(int j=0; j<nBlanks*2-2; j++)
System.out.print(' ');
} // end while globalStack not empty
System.out.println();
nBlanks /= 2;
while(localStack.isEmpty()==false)
globalStack.push( localStack.pop() );
} // end while isRowEmpty is false
System.out.println(
} // end displayTree()
} // end class Tree
class TreeApp
public static void main(String[] args) throws IOException
int value;
double val1;
String Line,Term;
BufferedReader input;
input = new BufferedReader (new FileReader ("one.txt"));
Tree theTree = new Tree();
val1=0.1;
while ((Line = input.readLine()) != null)
Term=Line;
//val1=Integer.parseInt{Term};
val1=val1+1;
//theTree.insert(Line, val1+0.1);
val1++;
System.out.println(Line);
System.out.println(val1);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
theTree.insert(50, 1.5);
theTree.insert(25, 1.2);
theTree.insert(75, 1.7);
theTree.insert(12, 1.5);
theTree.insert(37, 1.2);
theTree.insert(43, 1.7);
theTree.insert(30, 1.5);
theTree.insert(33, 1.2);
theTree.insert(87, 1.7);
theTree.insert(93, 1.5);
theTree.insert(97, 1.5);
while(true)
putText("Enter first letter of ");
putText("show, insert, find, delete, or traverse: ");
int choice = getChar();
switch(choice)
case 's':
theTree.displayTree();
break;
case 'i':
putText("Enter value to insert: ");
value = getInt();
theTree.insert(value, value + 0.9);
break;
case 'f':
putText("Enter value to find: ");
value = getInt();
Node found = theTree.find(value);
if(found != null)
putText("Found: ");
found.displayNode();
putText("\n");
else
putText("Could not find " + value + '\n');
break;
case 'd':
putText("Enter value to delete: ");
value = getInt();
boolean didDelete = theTree.delete(value);
if(didDelete)
putText("Deleted " + value + '\n');
else
putText("Could not delete " + value + '\n');
break;
case 't':
putText("Enter type 1, 2 or 3: ");
value = getInt();
theTree.traverse(value);
break;
default:
putText("Invalid entry\n");
} // end switch
} // end while
} // end main()
public static void putText(String s)
System.out.print(s);
System.out.flush();
public static String getString() throws IOException
InputStreamReader isr = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(isr);
String s = br.readLine();
return s;
public static char getChar() throws IOException
String s = getString();
return s.charAt(0);
public static int getInt() throws IOException
String s = getString();
return Integer.parseInt(s);
} // end class TreeAppString str = "Hello";
int index = 0, len = 0;
len = str.length();
while(index < len) {
System.out.println(str.charAt(index));
index++;
} -
Having trouble finding the height of a Binary Tree
Hi, I have an ADT class called DigitalTree that uses Nodes to form a binary tree; each subtree only has two children at most. Each node has a "key" that is just a long value and is placed in the correct position on the tree determined by its binary values. For the height, I'm having trouble getting an accurate height. With the data I'm using, I should get a height of 5 (I use an array of 9 values/nodes, in a form that creates a longest path of 5. The data I use is int[] ar = {75, 37, 13, 70, 75, 90, 15, 13, 2, 58, 24} ). Here is my code for the whole tree. If someone could provide some tips or clues to help me obtain the right height value, or if you see anything wrong with my code, it would be greatly aprpeciated. Thanks!
public class DigitalTree<E> implements Copyable
private Node root;
private int size;
public DigitalTree()
root = null;
size = 0;
public boolean add(long k)
if(!contains(k))
if(this.size == 0)
root = new Node(k);
size++;
System.out.println(size + " " + k);
else
String bits = Long.toBinaryString(k);
//System.out.println(bits);
return add(k, bits, bits.length(), root);
return true;
else
return false;
private boolean add(long k, String bits, int index, Node parent)
int lsb;
try
lsb = Integer.parseInt(bits.substring(index, index - 1));
catch(StringIndexOutOfBoundsException e)
lsb = 0;
if(lsb == 0)
if(parent.left == null)
parent.left = new Node(k);
size++;
//System.out.println(size + " " + k);
return true;
else
return add(k, bits, index-1, parent.left);
else
if(parent.right == null)
parent.right = new Node(k);
size++;
//System.out.println(size + " " + k);
return true;
else
return add(k, bits, index-1, parent.right);
public int height()
int leftHeight = 0, rightHeight = 0;
return getHeight(root, leftHeight, rightHeight);
private int getHeight(Node currentNode, int leftHeight, int rightHeight)
if(currentNode == null)
return 0;
//else
// return 1 + Math.max(getHeight(currentNode.right), getHeight(currentNode.left));
if(currentNode.left == null)
leftHeight = 0;
else
leftHeight = getHeight(currentNode.left, leftHeight, rightHeight);
if(currentNode.right == null)
return 1 + leftHeight;
return 1 + Math.max(leftHeight, getHeight(currentNode.right, leftHeight, rightHeight));
public int size()
return size;
public boolean contains(long k)
String bits = Long.toBinaryString(k);
return contains(k, root, bits, bits.length());
private boolean contains(long k, Node currentNode, String bits, int index)
int lsb;
try
lsb = Integer.parseInt(bits.substring(index, index - 1));
catch(StringIndexOutOfBoundsException e)
lsb = 0;
if(currentNode == null)
return false;
else if(currentNode.key == k)
return true;
else
if(lsb == 0)
return contains(k, currentNode.left, bits, index-1);
else
return contains(k, currentNode.right, bits, index-1);
public Node locate(long k)
if(contains(k))
String bits = Long.toBinaryString(k);
return locate(k, root, bits, bits.length());
else
return null;
private Node locate(long k, Node currentNode, String bits, int index)
int lsb;
try
lsb = Integer.parseInt(bits.substring(index, index - 1));
catch(StringIndexOutOfBoundsException e)
lsb = 0;
if(currentNode.key == k)
return currentNode;
else
if(lsb == 0)
return locate(k, currentNode.left, bits, index-1);
else
return locate(k, currentNode.right, bits, index-1);
public Object clone()
DigitalTree<E> treeClone = null;
try
treeClone = (DigitalTree<E>)super.clone();
catch(CloneNotSupportedException e)
throw new Error(e.toString());
cloneNodes(treeClone, root, treeClone.root);
return treeClone;
private void cloneNodes(DigitalTree treeClone, Node currentNode, Node cloneNode)
if(treeClone.size == 0)
cloneNode = null;
cloneNodes(treeClone, currentNode.left, cloneNode.left);
cloneNodes(treeClone, currentNode.right, cloneNode.right);
else if(currentNode != null)
cloneNode = currentNode;
cloneNodes(treeClone, currentNode.left, cloneNode.left);
cloneNodes(treeClone, currentNode.right, cloneNode.right);
public void printTree()
System.out.println("Tree");
private class Node<E>
private long key;
private E data;
private Node left;
private Node right;
public Node(long k)
key = k;
data = null;
left = null;
right = null;
public Node(long k, E d)
key = k;
data = d;
left = null;
right = null;
public String toString()
return "" + key;
}You were on the right track with the part you commented out; first define a few things:
1) the height of an empty tree is nul (0);
2) the height of a tree is one more than the maximum of the heights of the left and right sub-trees.
This translates to Java as a recursive function like this:
int getHeight(Node node) {
if (node == null) // definition #1
return 0;
else // definition #2
return 1+Math.max(getHeight(node.left), getHeight(node.right));
}kind regards,
Jos -
I have a project where I need to build a binary tree with random floats and count the comparisons made. The problem I'm having is I'm not sure where to place the comaprison count in my code. Here's where I have it:
public void insert(float idata)
Node newNode = new Node();
newNode.data = idata;
if(root==null)
root = newNode;
else
Node current = root;
Node parent;
while(true)
parent = current;
if(idata < current.data)
comp++;
current = current.leftc;
if(current == null)
parent.leftc = newNode;
return;
else
current = current.rightc;
if(current == null)
parent.rightc = newNode;
return;
}//end insertDo I have it in the right place? Also, if I'm building the tree for 10,000 numbers would I get a new count for each level or would I get one count for comparisons?? I'd appreciate anyone's help on this.You never reset the comp variable, so each timeyou
insert into the tree, it adds the number ofinserts
to the previous value.Yes, or something like that. I'm not sure what theOP
really means.Yeah, it's hard to be sure without seeing the rest of
the code.Sorry, I thought I had already posted my code for you to look at.
Here's a copy of it:
class Node
public float data;
public Node leftc;
public Node rightc;
public class Btree
private Node root;
private int comp;
public Btree(int value)
root = null;
public void insert(float idata)
Node newNode = new Node();
newNode.data = idata;
if(root==null)
root = newNode;
else
Node current = root;
Node parent;
while(true)
parent = current;
comp++;
if(idata < current.data)
current = current.leftc;
if(current == null)
parent.leftc = newNode;
return;
else
current = current.rightc;
if(current == null)
parent.rightc = newNode;
return;
}//end insert
public void display()
//System.out.print();
System.out.println("");
System.out.println(comp);
} //end Btree
class BtreeApp
public static void main(String[] args)
int value = 10000;
Btree theTree = new Btree(value);
for(int j=0; j<value; j++)
float n = (int) (java.lang.Math.random() *99);
theTree.insert(n);
theTree.display();
} -
How to design databse for binary tree
kindly help in desiging databse for binary tree and also to retrive data from database.
Since you're not asking about Java, you'll probably get more responses by posting this in a database forum.
-
Binary tree for parsing algebraic expressions
hi all
i have a project to do.. i need to read in an algebraic expression, parse it and form a binary tree. later use that tree to evaluate the expressions when the actual value for those variables are passed..
can anyone tell me how to go about doing this.
im a beginner in java..
tksfirst of, your going to need three stacks. The implementation of a stack in JAVA is something that's easy to find, do a forum search. Your going to need a Binary Node as well. One stack will hold the operator elements of your algebraic expression, another will hold the numeric values, and the final will hold your binary nodes:
expression: 4 + 6 - (6 * 9)
now there are some rules that should be followed. Whenever a closing parenthesis is encountered ")", pop an operator, pop two numbers, and create the corresponding binary node.
order of operations:
push 4 onto numberStack
push + onto operatorStack
push 6 onto numberStack
push - onto operatorStack
push ( onto operator Stack
push 6 onto numberStack
push * onto operatorStack
push 9 onto numberStack
")" encountered
Now, your stacks look something like this:
operatorStack: [ +, -, (, *, ) ]
numberStack: [ 4, 6, 6, 9 ]
pop 9 and 6 from numberStack, pop * from operatorStack
build a binaryNode using these three elements
push this node onto the binaryNodeStack
I.E. using the expression above:
/ \ is the resulting binary node once the ")" is received.
6 9
etc.. there are some rules regarding when to pop and build binary nodes, it's been a while since i did this assignment and frankly my brain hurts, hope this gets you started, good luck. -
Binary Tree Implementations - why both key and value?
Hi there!
I'm sitting here implementing a binary tree, and I was just wondering why most of the binary tree examples encapsulate both a key AND a value in their nodes. Wouldn't it be sufficient to just store comparable objects in the nodes (or provide a comparator for alternative ordering)?
Thanks again, Oliver
P.S.:Any suggestions on good books (free E-Books preferred :-)) on ADTs and algorithms? I'm reading 'Data Structures And Algorithms In Java' by Robert Lafore and not very happy with it (the examples are just plain awful).Trollhorn wrote:
Hi there!
I'm sitting here implementing a binary tree, and I was just wondering why most of the binary tree examples encapsulate both a key AND a value in their nodes. Wouldn't it be sufficient to just store comparable objects in the nodes (or provide a comparator for alternative ordering)?Yes.
Thanks again, Oliver
P.S.:Any suggestions on good books (free E-Books preferred :-)) on ADTs and algorithms? I'm reading 'Data Structures And Algorithms In Java' by Robert Lafore and not very happy with it (the examples are just plain awful).As online resources:
[http://www.cs.princeton.edu/introcs/44st/]
[http://ocw.mit.edu/OcwWeb/Electrical-Engineering-and-Computer-Science/6-006Spring-2008/CourseHome/index.htm]
I don't know of any eBooks on the subject, but I can recommend an excellent hard copy book:
Introduction To Algorithms, by Cormen et al. [http://highered.mcgraw-hill.com/sites/0070131511/information_center_view0/] -
Binary tree inorder traversal without recursion
Using Java, write a method that does an in-order traversal of a binary tree WITHOUT using recursion. based on the following code
BTreeNode.java
public class BTreeNode
public BTreeNode LEFT;
public BTreeNode RIGHT;
public String VALUE;
BTreeUtil.java
public class BTreeUtil
public static void listNodes(BTreeNode a_oRootNode)
// insert code here...
}This is definitely the wrong place to post this. Nevertheless you'll have to use a stack. While traversing down the tree you push the parents onto the stack.
stephan -
Binary tree using inorder traversal algorithm
I need to draw a Binary tree using Inorder traversal algorithm.. in java applets using rectangles and ellipse objects.. can anyone help me about this ? I will be really thankful to yu
I think this is my psychic Sunday, so here's my attempt at answering
this vaguely stated question. First have a look at this fine piece of
ASCII art:-------------------------------------------- ^ ^
| A T | | |
| | | root
---------L-----------------------R---------+ | v
| B | C | |
| | | |
| | | height
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
| | | |
-------------------------------------------+ v
<--------------------width------------------->Suppose you have a rectangle 'width' wide and 'height' high. The root
of the tree can be drawn at position T and (if present), two lines can be
drawn to the positions L and R respectively. Now recursively call your
same method using the computed rectangle A and B for the left and
right subtrees L and R respectively.
kind regards,
Jos
Maybe you are looking for
-
Removing drag functionality of column in OBIEE 11g
Hi all, Can any one say me how to remove the draging functionality for the columns in OBIEE 11g ? It is creating an issue for me when i hide the columns in pivot and has only rows over there. It is creating one more layer on the top of the measures.
-
Step by Step XI practical scenarios
Hi! I have first practical experience working with SAP XI 7.0 and searching for practical Step by Step scenarios: - IDOC to IDOC scenarios - ABAP or Java Proxy scenarios - scenarios with SOAP adapter Has some one seen in SDN-blog or in other sources
-
Task Flow Return Listener not fire when FK association fields set manually
Guys and Gals, I've spent two solid days on this and I'm not sure why my task flow return listener is not firing. I start by selecting a row in a table. I then click a "Convert" button which converts the Quote document into a Sales document. I then p
-
The flash of my new iphone5 camera dosent work. What can i do?
When i take a photo with flash on the flash dont work at all. Can somebody tell me what to do please?. Thanks.
-
Custom validation & IsNumber javascript
Hi How can we add custom validation in the "Edit an element" on Portal9as By example to validate that the new image file name is unique How can we use the IsNumber javascript from the shared objects Can we add custom validation when we create new att