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
Similar Messages
-
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. -
Binary Tree in Java - ******URGENT********
HI,
i want to represent a binary tree in java. is there any way of doing that.
thanx
sraphsonHI,
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 -
Does anyone know how to create a binary file in Java.
in C i can do an fopen("filename" , "rb") i cannot find a equivalent java binary file stream.
ThanksThe following code is part of my FileIO applet. This method allows the user to download any file from my server and save it on his/her disk, the download is accomplished by doing a byte-read and byte-write (byte mover as I'd call it). This example illustrates how you can read and write binary files in Java:
public void aok_DownLoad(String inputFile, String outputFile) {
try {
URL url=new URL(inputFile);
InputStream in;
in=url.openStream();
BufferedInputStream reader=new BufferedInputStream(in,4096);
FileOutputStream out=new FileOutputStream(outputFile);
BufferedOutputStream writer=new BufferedOutputStream(out,4096);
byte[] buf=new byte[4096];
int byteRead;
while ((byteRead=reader.read(buf,0,4096))>=0) {writer.write(buf,0,byteRead);}
reader.close();
writer.flush();
writer.close();
catch (Throwable exception) {
exception.printStackTrace();
}V.V.
PS: in this posting the code is posted in a different manner so that the > sign is not converted to & gt ; by the forum's software -
A Binary Tree Implementation in ABAP
Hi,
Can any one explaine me how to create a binary tree of random numbers with dynamic objects.
Thanks,
Manjula.Hi manjula,
This sample code uses dynamic objects to create a binary tree of random numbers as per your requirement ...pls go through It.
It stores numbers on the left node or right node depending on the value comparison with the current value. There are two recursive subrotines used for the building of the tree and printing through the tree.
For comparison purpose, the same random numbers are stored and sorted in an internal table and printed.
*& Report YBINTREE - Build/Print Binary Tree of numbers *
report ybintree .
types: begin of stree,
value type i,
left type ref to data,
right type ref to data,
end of stree.
data: tree type stree.
data: int type i.
data: begin of rnd occurs 0,
num type i,
end of rnd.
start-of-selection.
do 100 times.
generate random number between 0 and 100
call function 'RANDOM_I4'
exporting
rnd_min = 0
rnd_max = 100
importing
rnd_value = int.
store numbers
rnd-num = int.
append rnd.
build binary tree of random numbers
perform add_value using tree int.
enddo.
stored numbers are sorted for comparison
sort rnd by num.
print sorted random numbers
write: / 'Sorted Numbers'.
write: / '=============='.
skip.
loop at rnd.
write: rnd-num.
endloop.
skip.
print binary tree. This should give the same result
as the one listed from the internal table
write: / 'Binary Tree List'.
write: / '================'.
skip.
perform print_value using tree.
skip.
*& Form add_value
text - Build tree with value provided
-->TREE text
-->VAL text
form add_value using tree type stree val type i.
field-symbols: <ltree> type any.
data: work type stree.
if tree is initial. "When node has no values
tree-value = val. " assign value
clear: tree-left, tree-right.
create data tree-left type stree. "Create an empty node for left
create data tree-right type stree. "create an empty node for right
else.
if val le tree-value. "if number is less than or equal
assign tree-left->* to <ltree>. "assign the left node to fs
call add_value recursively with left node
perform add_value using <ltree> val.
else. "if number is greater
assign tree-right->* to <ltree>. "assign the right node to fs
call add_value recursively with right node
perform add_value using <ltree> val.
endif.
endif.
endform. "add_value
*& Form print_value
text - traverse tree from left-mid-right order
automatically this will be sorted list
-->TREE text
form print_value using tree type stree.
field-symbols: <ltree> type any.
if tree is initial. "node is empty
else. "non-empty node
assign tree-left->* to <ltree>. "left node
perform print_value using <ltree>. "print left
write: tree-value. "print the current value
assign tree-right->* to <ltree>. "right node
perform print_value using <ltree>. "print right
endif.
endform. "print_value
pls reward if helps,
regards. -
Binary Tree search and print methods
Hello, I'm trying to create a binary tree from inputs of a user. I believe I have the tree set up right because it shows no errors, but I'm getting an error message with a line of code. I cannot figure out what I am doing wrong. Also, I need to create a print method, which prints the tree's entries and a search method which would search the tree for certain record.
public class TreeNode
public static String empName = null;
public static int empNumber;
public static String nextRec = null;
TreeNode left;
String Name;
int Number;
TreeNode right;
public static void main(String[] args)
VRead in = new VRead();
VWrite out = new VWrite();
System.out.println("Enter Choice: ");
System.out.println("A: Enter Employee Information.");
System.out.println("B: Search For Employee.");
System.out.println("C: Print Entire Tree.");
System.out.println("D: Exit.");
System.out.println("_______________________________");
char command = in.readChar();
System.out.println();
switch (command)
case 'A':
case 'a':
inputInfo(in, out);
break;
case 'B':
case 'b':
break;
case 'C':
case 'c':
break;
case 'D':
case 'd':
System.exit(0);
break;
public static void inputInfo(VRead in, VWrite out)
out.write("Enter Employee Name: ");
empName = in.readString();
out.write("Enter Employee Number: ");
empNumber = in.readInt();
System.out.println();
System.out.println();
System.out.println("Enter Choice: ");
System.out.println("A: Enter Employee Information.");
System.out.println("B: Search For Employee.");
System.out.println("C: Print Entire Tree.");
System.out.println("D: Exit.");
System.out.println("_______________________________");
char command = in.readChar();
System.out.println();
switch (command)
case 'A':
case 'a':
inputInfo(in, out);
break;
case 'B':
case 'b':
break;
case 'C':
case 'c':
break;
case 'D':
case 'd':
System.exit(0);
break;
public TreeNode(String empName, int empNumber)
Name = empName;
Number = empNumber;
left = null;
right = null;
public class Tree
TreeNode Root;
public void Tree(String RootNode)
// Errors come from next line
Root = new TreeNode(RootNode, Name, Number);
public void Insert(String Name, int Number)
InsertNode(Root, Name, Number);
public void InsertNode(TreeNode t, String empName, int empNumber)
if (t == null)
t = new TreeNode(empName, empNumber);
else
if (empName.compareTo(t.Name) < 0)
InsertNode(t.left, empName, empNumber);
else if (empName.compareTo(t.Name) > 0)
InsertNode(t.right, empName, empNumber);
else if (empName.compareTo(t.Name) == 0)
System.out.println("Entered node that was already in Tree");
}im sure its something simple, i seem to always look over the small stuff. But i could really use some help on the print and search method tooJust having a quick look over it, and it looks like you are trying to add an extra argument in the TreeNode() method (unless there is a bit of overloading and there is a second treenode method in there) As it is TreeNode only accepts two argumets you have 3
As for printing the tree you would need to flatten it, that is an in order traversal of the tree.
FWIW
I just finished a project at uni that involved at frist writing a BST and then an AVL tree. the full point of these things seems to be to keep students awake at night*
*Before anyone flames, it's a joke
G -
Hello,
The problem I'm having is how to empty a binary tree. Here is my code for MyBinaryTree:
public class MyBinaryTree implements BinaryTree {
private BinaryTreeNode root;
protected static int numNodes;
private static String tree = "";
* Constructor that creates a binary tree with a root.
* @param r The root node
* @param num The number of nodes
public MyBinaryTree(BinaryTreeNode r, int num) {
root = r;
numNodes = num;
* Method to make the binary tree empty.
public void makeEmpty() {
root.left = null;
root.right = null;
root = new BinaryTreeNode(null,null,null,null,null);
numNodes = 0;
* Method to make a root with key k and element el.
* @param k The key of the root
* @param el The element in the root
public void makeRoot(Comparable k, Object el) {
root = new BinaryTreeNode(k,el);
numNodes++;
* Method to return the root of the binary tree.
* @return The root of the tree
public BinaryTreeNode root() {
return root;
* Method to return the left child of a node.
* @param node The node whose left child is wanted.
* @return The left child of the node
* @see NoNodeException
public BinaryTreeNode leftChild(BinaryTreeNode node) throws NoNodeException {
if (node.left == null) throw new NoNodeException("No left child!");
else return node.leftChild();
* Method to set the left child of node "node".
* @param node The node to be given a left child
* @param child The node to be set as left child
public void setLeftChild(BinaryTreeNode node, BinaryTreeNode child) {
node.setLeftChild(child);
numNodes++;
* Method to return the right child of a node.
* @param node The node whose right child is wanted.
* @return The right child of the node
* @see NoNodeException
public BinaryTreeNode rightChild(BinaryTreeNode node) throws NoNodeException{
if (node.right == null) throw new NoNodeException("No right child!");
else return node.rightChild();
* Method to set the right child of node "node".
* @param node The node to be given a right child
* @param child The node to be set as right child
public void setRightChild(BinaryTreeNode node, BinaryTreeNode child) {
node.setRightChild(child);
numNodes++;
* Method to return the parent of a node.
* @param node The node whose parent is wanted.
* @return The parent of the node
* @see NoNodeException
public BinaryTreeNode parent(BinaryTreeNode node) throws NoNodeException {
if (node.p == null) throw new NoNodeException("No parent!");
else return node.parent();
* Method to set the parent of node "node".
* @param node The node to be given a parent
* @param pt The node to be set as parent
public void setparent(BinaryTreeNode node, BinaryTreeNode pt) {
node.setParent(pt);
numNodes++;
* Method to return the key of the specified node.
* @param node The node with the key to be returned
* @return The key of the node
public Comparable getKey(BinaryTreeNode node) {
return node.getKey();
* Method to set the key of the specified node.
* @param node The node for which the key will be set.
* @param k The key to be set.
public void setKey(BinaryTreeNode node, Comparable k) {
node.setKey(k);
* Method to get the element in the specified node.
* @param node The node with the element to be returned.
* @return The element in the node.
public Object getElement(BinaryTreeNode node) {
return node.getElement();
* Method to put an element into the specified node.
* @param node The node that will have an element put in it.
* @param o The element to be inserted.
public void setElement(BinaryTreeNode node, Object o) {
node.setElement(o);
* Method to add a left child to the specified node.
* @param theNode The node that the left child will be added to.
* @param k The key associated with the left child.
* @param el The element in the left child.
public void addLeftChild (BinaryTreeNode theNode, Comparable k, Object el) {
BinaryTreeNode temp = new BinaryTreeNode(k,el);
temp.setParent(theNode);
theNode.setLeftChild(temp);
numNodes++;
* Method to add a right child to the specified node.
* @param theNode The node that the right child will be added to.
* @param k The key associated with the right child.
* @param el The element in the right child.
public void addRightChild (BinaryTreeNode theNode, Comparable k, Object el) {
BinaryTreeNode temp = new BinaryTreeNode(k,el);
temp.setParent(theNode);
theNode.setRightChild(temp);
numNodes++;
* Method to remove the left child of the specified node.
* @param theNode The node which the left child will be removed.
public void removeLeftChild(BinaryTreeNode theNode) {
((BinaryTreeNode)(theNode.left)).p = null;
theNode.left = null;
numNodes--;
* Method to remove the right child of the specified node.
* @param theNode The node which the right child will be removed.
public void removeRightChild(BinaryTreeNode theNode) {
((BinaryTreeNode)(theNode.right)).p = null;
theNode.right = null;
numNodes--;
* Private method to perform an inorder traversal on the tree.
* @param t A MyBinaryTree object
* @param n The starting node.
private static String inorderPrint(MyBinaryTree t, BinaryTreeNode n) {
String spaces = "";
for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
if (n.left != null || n.right != null) inorderPrint(t,t.leftChild(n));
tree += spaces + n.getElement();
if (n.left != null || n.right != null) inorderPrint(t,t.rightChild(n));
return tree;
* Private method to perform an inorder traversal on the tree.
* @param t A MyBinaryTree object
* @param n The starting node.
* @param pos The current position in the tree.
* @return A tree with an asterix beside the current position
private static String inorderPrint2(MyBinaryTree t, BinaryTreeNode n,
BinaryTreeNode pos) {
String spaces = "";
for (int i = 0; i < (numNodes - 1)/2; i++) spaces += " ";
if (n.left != null || n.right != null) inorderPrint2(t,t.leftChild(n),pos);
if (n.getElement() == pos.getElement()) tree += spaces + n.getElement() + "*";
else tree += spaces + n.getElement();
if (n.left != null || n.right != null) inorderPrint2(t,t.rightChild(n),pos);
return tree;
* Method to return a String representation of the binary tree.
* @return String representation of the binary tree
public String toString() {
if (root.getElement() == null) return "*** Tree is empty ***";
else {
MyBinaryTree temp = new MyBinaryTree(root,numNodes);
return inorderPrint(temp,root);
* Method to return a String of the binary tree with an asterix beside the
* current position.
* @param currentPosition The current position.
* @return A String of the tree with an asterix by the current position
public String toString(BinaryTreeNode currentPosition) {
if (root.getElement() == null) return "*** Tree is empty ***";
else {
MyBinaryTree temp = new MyBinaryTree(root,numNodes);
return inorderPrint2(temp,root,currentPosition);
}Those are all the methods I'm allowed to have. When I run makeEmpty, it seems to work, but then if I do makeRoot, the old tree prints again. It's quite bizarre. Any tips on how to empty the tree correctly?Here is the BinaryTreeNode code.
public class BinaryTreeNode {
// Instance variables (Note: they are all "private")
protected Comparable key; // The key at this node
protected Object element; // The data at this node
protected BinaryTreeNode left; // Left child
protected BinaryTreeNode right; // Right child
protected BinaryTreeNode p; // The Parent
// Constructors
BinaryTreeNode( Comparable theKey, Object theElement, BinaryTreeNode lt,
BinaryTreeNode rt, BinaryTreeNode pt ) {
key = theKey;
element = theElement;
left = lt;
right = rt;
p = pt;
BinaryTreeNode( Comparable theKey, Object theElement) {
key = theKey;
element = theElement;
left = null;
right = null;
p = null;
// return the key attached to this node
public Comparable getKey() {
return key;
// set the key attached to this node to be Comparable k
public void setKey(Comparable k) {
key = k;
// return the element attached to this node
public Object getElement() {
return element;
// set the element attached to this node to be Object o
public void setElement(Object o) {
element = o;
// return left child
public BinaryTreeNode leftChild() {
return left;
// set left child to be node n
public void setLeftChild(BinaryTreeNode n) {
left = n;
// return right child
public BinaryTreeNode rightChild() {
return right;
// set right child to be node n
public void setRightChild(BinaryTreeNode n) {
right = n;
// return parent
public BinaryTreeNode parent() {
return p;
// set parent to be node n
public void setParent(BinaryTreeNode n) {
p = n;
} -
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. -
How to create a Folder Tree in Exchange Server from a Java progarm.
hi all,
I am using Microsoft Exchange Server 2000. I have a requirement of creating the following things from a Java program.
1) Creating a Folder Tree
2) Creating a Mailbox Store
3) Creating a Public Store
4) Creating a Recipient Policy
5) Creating a Storage Group
6) Creating a Mail-Enabled Recipient
7) Adding a new UPN suffixes
If any of you have worked on such requirement can you please provide me with some information regarding the same.
Thanks & Regards
AnilAny luck with this Anil?
I would like to query exchange for the list or recipients on a given mailing list.
Please inform if there is any documentation that may be helpful. -
Creating Insert Method for a binary tree
I have code for a binary tree http://sourcepost.sytes.net/sourceview.aspx?source_id=5046
I'm trying to create an insert method that will accept an element and insert it into my binary tree. The main purpose of this is to test my traversal functions, intrav(), postrav(), pretrav(). I have another class that will create 10 random numbers and call insert() to insert them into my tree. Can anyone help me write this method?anyone?
-
Non recursive preorder traversal of binary tree
hi,
I am trying to implement a non-recursive traversal of binary tree. I already know the recursive one.
I am trying to do it by using a Stack.
I begin by Pushing the root of an element on to a stack, and then run a while loop in which i pop an element of the stack and get its children from right to left. and push it in the same order on to the stack. So during the next iteration of my while loop the top most element gets popped and its children and pushed on to the stack in the above manner.
but when i pop an element from a stack its popped as an object so i dont know how to access its children.
help me i am really stuck.Hi, I suppose you have something like this :
class Stack {
public void push( Object object ) throws ... { ... }
public Object pop() throws ... { ... }
class Element {
Element elem;
stack.push(elem);
/* because pop() method return an object of type Object
** if you are sure that your stack only contains Element object
** then you need to cast (change the type of) what the pop() method
** returns in this way :
elem = (Element)stack.pop();
...further reading on casting will be a good idea anyway. -
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
Maybe you are looking for
-
Good morning experts, can any one please suggest me a sample functionmodule code to upload excel based file in to sem/bps cube.using web interface.
-
Hi, I have implemented pagination for the table. I have start,previous,next,last buttons in the bottom of the table. It is working fine. Generally if i click on column for sorting it will sort the columns in which where we are.(Suppose if we are in s
-
Setting maxP2PStreamPublish for a room
Hi, How do I set the parameter maxP2PStreamPublish of StreamManager for a room to enable more than 3 p2p streams to be published by a publisher? Also, what are the implications of setting this value to a very high value?? Thanks, Soumik
-
Pricipal authorization.
Hi Bea weblogic Gurus, i need some information about the weblogic security checking. In web.xml and weblogic.xml i have assigned one Pricipal name for a servlet/jsp. what will happen if the user who requested the servlet/jsp doesn't have the principa
-
TS3212 Why do I get a access denied message?
Why do I recieve a message that tells me access denied?