Help with a binary tree
I'm writing a binary tree class and am having some trouble with the Insert function. Here is the code for the TreeNode class...
public class TreeNode
TreeNode Left;
TreeNode Right;
String Name;
public TreeNode(String NodeName)
Left = null;
Right = null;
Name = NodeName;
}And this is the code for the Tree class...
public class Tree
TreeNode Root;
public Tree(String RootNode)
Root = new TreeNode(RootNode);
public void Insert(String Name)
InsertNode(Root, Name);
public void InsertNode(TreeNode t, String NodeName)
if (t == null)
t = new TreeNode(NodeName);
else
if (NodeName.compareTo(t.Name) < 0)
InsertNode(t.Left, NodeName);
else if (NodeName.compareTo(t.Name) > 0)
InsertNode(t.Right, NodeName);
else if (NodeName.compareTo(t.Name) == 0)
System.out.println("Entered node that was already in Tree");
}When I enter a new node into a Tree containing just the root, it follows the recursion through once, then creates the new TreeNode as it should. However, the new node is not really recognized by the tree because when I try to insert another node, it only finds the root in the tree and only goes through one recursion. What's wrong?
I believe t.Left (or t.Right) is getting set in the line
t = new TreeNode(NodeName);
Since it is a recursive function, when it is called the second time, the "t" that is passed in is actually the original t.left (I think), which is getting set then.
Similar Messages
-
Help loading a binary tree from file
Hi all,
So I am working on making a 20 question game using a binary tree. I have set it up so each time the user plays, if the computer cannot guess what they are thinking of, they tell the computer and it saves it. I am saving the tree in a text file recursively, in a format that looks something like this:
Do you use it outside?
a shovel
[null]
[null]
is it round?
a ball
[null]
[null]
a TV
[null]
[null]
The problem is now, I am having a very hard time rebuilding the tree when the user restarts the game. As you can see, the "{" indicates the beginning of a path and the "}" is the end. Can someone suggest a nice way to load this back up into my data structure? Thanks!!Cross-post here: [http://www.java-forums.org/java-2d/14237-help-loading-binary-tree-file.html]
Recommended looking into XML -
Help with Minimum Spanning Tree
Hello, I need some help with Kruskal's Algorithm, Thanks. This is the link:
http://forum.java.sun.com/thread.jsp?forum=31&thread=325804&tstart=0&trange=15I don't think the error is mine. I copied the link just as it shows on the address bar.
http://forum.java.sun.com/thread.jsp?forum=31&thread=325804 -
hi guys here's the problem i'm having:
I have a class called Node that I am building a tree out of. Node is a very simple structure, has three parts: element, left and right, with element being the top. Then I have a class called converterTree. This class will take in a postfix (polish notation) string and convert it into a tree through tokenizing etc. for an ultimate calculator class. The code I will post below uses a stack implementation to do so. It should: add all operands to the stack until it hits an operator, then make a new node with the operator as the element, and the left and right are the top and second stack objects respectively. then it pushes this entire tree back onto the stack and keeps going, at each step creating a new tree and linking it to the old one. The problem is that for some reason when I get the top node back in the return, it comes back as only that node, as if all the things it referenced are gone. You wont be able to run the code below since it needs some other classes, but in my main method where all those printlns are know that the return comes back as -, null, null, null, null, null, null with - being the thing on the stack that is SUPPOSED to link to the rest of them, yet for some reason they all come back null? any suggestions? heres the code:
import java.util.StringTokenizer;
public class ConverterTree
String stringToConvert;
static QueueLi returnQueue = new QueueLi();
public ConverterTree (String toConvert)
stringToConvert = toConvert;
public static boolean isOperator(String op)
char c = op.charAt(0);
return (c == '*'|| c =='/' || c == '+' || c =='-');
public static boolean isLParen (String op )
char c = op.charAt(0);
return c== '(';
public static boolean isRParen (String op)
char c = op.charAt(0);
return c == ')';
public static boolean isSpace(String op)
char c = op.charAt(0);
return c == ' ';
public static boolean isOperand (String op)
return (!( isOperator(op) || isLParen(op) || isRParen(op) || isSpace(op)));
public Node toTree (String toConvert)
String delims = new String("+-/* ");
StringTokenizer tokenizer = new StringTokenizer(stringToConvert, delims, true);
String token = new String();
StackLi stack = new StackLi();
while (tokenizer.hasMoreTokens())
token = tokenizer.nextToken();
System.out.println("token: " + token);
if (isOperand(token))
ListNode node1 = new ListNode(token);
System.out.println("This operand is being pushed: " + token);
stack.push(token);
else if (isOperator(token))
Node op2 = new Node(stack.topAndPop());
Node op1 = new Node(stack.topAndPop());
Node opTree = new Node(token, op1, op2);
System.out.println("node and left and right: " + opTree.element + opTree.left + opTree.right);
stack.push(opTree);
System.out.println("node and left and right: " + opTree.element + opTree.left + opTree.right);
Node returnNode = new Node(stack.topAndPop());
return returnNode;
public static void main (String [] args)
String toConvert1 = "2 5 + 6 8 + -";
ConverterTree treeTest = new ConverterTree(toConvert1);
Node testNode = treeTest.toTree(toConvert1);
Node right = new Node(testNode.right);
Node left = new Node(testNode.left);
System.out.println(testNode);
System.out.println(left);
System.out.println(right);
System.out.println(left.left);
System.out.println(left.right);
System.out.println(right.left);
System.out.println(right.right);
}hi guys here's the problem i'm having:
I have a class called Node that I am building a tree out of. Node is a very simple structure, has three parts: element, left and right, with element being the top. Then I have a class called converterTree. This class will take in a postfix (polish notation) string and convert it into a tree through tokenizing etc. for an ultimate calculator class. The code I will post below uses a stack implementation to do so. It should: add all operands to the stack until it hits an operator, then make a new node with the operator as the element, and the left and right are the top and second stack objects respectively. then it pushes this entire tree back onto the stack and keeps going, at each step creating a new tree and linking it to the old one. The problem is that for some reason when I get the top node back in the return, it comes back as only that node, as if all the things it referenced are gone. You wont be able to run the code below since it needs some other classes, but in my main method where all those printlns are know that the return comes back as -, null, null, null, null, null, null with - being the thing on the stack that is SUPPOSED to link to the rest of them, yet for some reason they all come back null? any suggestions? heres the code:
import java.util.StringTokenizer;
public class ConverterTree
String stringToConvert;
static QueueLi returnQueue = new QueueLi();
public ConverterTree (String toConvert)
stringToConvert = toConvert;
public static boolean isOperator(String op)
char c = op.charAt(0);
return (c == '*'|| c =='/' || c == '+' || c =='-');
public static boolean isLParen (String op )
char c = op.charAt(0);
return c== '(';
public static boolean isRParen (String op)
char c = op.charAt(0);
return c == ')';
public static boolean isSpace(String op)
char c = op.charAt(0);
return c == ' ';
public static boolean isOperand (String op)
return (!( isOperator(op) || isLParen(op) || isRParen(op) || isSpace(op)));
public Node toTree (String toConvert)
String delims = new String("+-/* ");
StringTokenizer tokenizer = new StringTokenizer(stringToConvert, delims, true);
String token = new String();
StackLi stack = new StackLi();
while (tokenizer.hasMoreTokens())
token = tokenizer.nextToken();
System.out.println("token: " + token);
if (isOperand(token))
ListNode node1 = new ListNode(token);
System.out.println("This operand is being pushed: " + token);
stack.push(token);
else if (isOperator(token))
Node op2 = new Node(stack.topAndPop());
Node op1 = new Node(stack.topAndPop());
Node opTree = new Node(token, op1, op2);
System.out.println("node and left and right: " + opTree.element + opTree.left + opTree.right);
stack.push(opTree);
System.out.println("node and left and right: " + opTree.element + opTree.left + opTree.right);
Node returnNode = new Node(stack.topAndPop());
return returnNode;
public static void main (String [] args)
String toConvert1 = "2 5 + 6 8 + -";
ConverterTree treeTest = new ConverterTree(toConvert1);
Node testNode = treeTest.toTree(toConvert1);
Node right = new Node(testNode.right);
Node left = new Node(testNode.left);
System.out.println(testNode);
System.out.println(left);
System.out.println(right);
System.out.println(left.left);
System.out.println(left.right);
System.out.println(right.left);
System.out.println(right.right);
} -
Need help with creating B*Tree XMLIndex on a structured object-relational xmltype column
The following is my schema:
CREATE TABLE TST_AUDIT_TBL
NOTE VARCHAR2(25 CHAR) null,
CHANGE_HISTORY XMLTYPE not null,
CHANGE_HISTORY_EXT XMLTYPE null
XMLTYPE COLUMN CHANGE_HISTORY STORE AS OBJECT RELATIONAL XMLSCHEMA "http://www.oracle.com/a.xsd" element "A"
XMLTYPE COLUMN CHANGE_HISTORY_EXT STORE AS CLOB XMLSCHEMA "http://www.oracle.com/a.xsd" element "AX"
XML Schema for the above is defined as follows:
<schema targetNamespace="http://www.oracle.com/a.xsd"
xmlns:a="http://www.oracle.com/a.xsd"
xmlns="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<complexType name="AuditExtType">
<sequence>
<element name="C" maxOccurs="unbounded" minOccurs="0">
<complexType>
<sequence>
<element type="string" name="CN"/>
<element type="string" name="OV" minOccurs="0" maxOccurs="1"/>
<element type="string" name="NV" minOccurs="0" maxOccurs="1"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<complexType name="AuditType">
<sequence>
<element type="string" name="M" maxOccurs="1" minOccurs="0"/>
<element type="string" name="O"/>
<element name="B" maxOccurs="1" minOccurs="0">
<complexType>
<sequence>
<element name="BC" minOccurs="1" maxOccurs="unbounded">
<complexType>
<sequence>
<element type="string" name="BN"/>
<element name="F" maxOccurs="unbounded" minOccurs="0">
<complexType>
<sequence>
<element type="string" name="FN"/>
<element type="string" name="OV" minOccurs="0" maxOccurs="1"/>
<element type="string" name="NV" minOccurs="0" maxOccurs="1"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
<element name="T" maxOccurs="1" minOccurs="0">
<complexType>
<sequence>
<element name="TL" minOccurs="1" maxOccurs="unbounded">
<complexType>
<sequence>
<element type="string" name="TN"/>
<element name="C" maxOccurs="unbounded" minOccurs="0">
<complexType>
<sequence>
<element type="string" name="CN"/>
<element type="string" name="OV" minOccurs="0" maxOccurs="1"/>
<element type="string" name="NV" minOccurs="0" maxOccurs="1"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
<element name="I" maxOccurs="1" minOccurs="0">
<complexType>
<sequence>
<element name="K" maxOccurs="unbounded" minOccurs="0">
<complexType>
<sequence>
<element type="string" name="N"/>
<element type="string" name="V"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<element name="A" type="a:AuditType"/>
<element name="AX" type="a:AuditExtType"/>
</schema>
I want to create a B*Tree XML Index on the above table for the following:
1. CN
2. TN
in the above schema.
Following the doc, this is what I am issuing:
SQL> CREATE INDEX audt_audit_idx1 ON TST_AUDIT_TBL(CHANGE_HISTORY) INDEXTYPE IS XDB.XMLINDEX PARAMETERS ('XMLTABLE IXTAB
2 XMLNAMESPACES(DEFAULT ''http://www.oracle.com/a.xsd''), ''/A'' COLUMNS COLUMN_NAME VARCHAR2(128) PATH ''A/T/TL/C/CN'' ');
CREATE INDEX audt_audit_idx1 ON TST_AUDIT_TBL(CHANGE_HISTORY) INDEXTYPE IS XDB.XMLINDEX PARAMETERS ('XMLTABLE IXTAB
ERROR at line 1:
ORA-29958: fatal error occurred in the execution of ODCIINDEXCREATE routine
ORA-19276: XPST0005 - XPath step specifies an invalid element/attribute name:
(A)
Not sure what is going wrong (and what would be a working xmlindex will look like?)Here goes...
1) Schema registration
begin
dbms_xmlschema.registerSchema(
schemaURL => 'http://www.oracle.com/a.xsd'
, local => true
, genTypes => true
, genTables => false
, enableHierarchy => dbms_xmlschema.ENABLE_HIERARCHY_NONE
, schemaDoc =>
'<schema targetNamespace="http://www.oracle.com/a.xsd"
xmlns:a="http://www.oracle.com/a.xsd"
xmlns="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified">
<complexType name="AuditExtType">
<sequence>
<element name="C" maxOccurs="unbounded" minOccurs="0">
<complexType>
<sequence>
<element type="string" name="CN"/>
<element type="string" name="OV" minOccurs="0" maxOccurs="1"/>
<element type="string" name="NV" minOccurs="0" maxOccurs="1"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<complexType name="AuditType">
<sequence>
<element type="string" name="M" maxOccurs="1" minOccurs="0"/>
<element type="string" name="O"/>
<element name="B" maxOccurs="1" minOccurs="0">
<complexType>
<sequence>
<element name="BC" minOccurs="1" maxOccurs="unbounded">
<complexType>
<sequence>
<element type="string" name="BN"/>
<element name="F" maxOccurs="unbounded" minOccurs="0">
<complexType>
<sequence>
<element type="string" name="FN"/>
<element type="string" name="OV" minOccurs="0" maxOccurs="1"/>
<element type="string" name="NV" minOccurs="0" maxOccurs="1"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
<element name="T" maxOccurs="1" minOccurs="0">
<complexType>
<sequence>
<element name="TL" minOccurs="1" maxOccurs="unbounded">
<complexType>
<sequence>
<element type="string" name="TN"/>
<element name="C" maxOccurs="unbounded" minOccurs="0">
<complexType>
<sequence>
<element type="string" name="CN"/>
<element type="string" name="OV" minOccurs="0" maxOccurs="1"/>
<element type="string" name="NV" minOccurs="0" maxOccurs="1"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
<element name="I" maxOccurs="1" minOccurs="0">
<complexType>
<sequence>
<element name="K" maxOccurs="unbounded" minOccurs="0">
<complexType>
<sequence>
<element type="string" name="N"/>
<element type="string" name="V"/>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
</element>
</sequence>
</complexType>
<element name="A" type="a:AuditType"/>
<element name="AX" type="a:AuditExtType"/>
</schema>'
end;
2) Table creation
CREATE TABLE TST_AUDIT_TBL
NOTE VARCHAR2(25 CHAR) null,
CHANGE_HISTORY XMLTYPE not null,
CHANGE_HISTORY_EXT XMLTYPE null
XMLTYPE COLUMN CHANGE_HISTORY STORE AS OBJECT RELATIONAL XMLSCHEMA "http://www.oracle.com/a.xsd" element "A"
XMLTYPE COLUMN CHANGE_HISTORY_EXT STORE AS CLOB XMLSCHEMA "http://www.oracle.com/a.xsd" element "AX"
3) Retrieving the nested table and column related to the target element :
SQL> select dbms_xmlstorage_manage.xpath2TabColMapping(
2 owner_name => 'DEV'
3 , table_name => 'TST_AUDIT_TBL'
4 , column_name => 'CHANGE_HISTORY'
5 , xpath => '/A/T/TL/C/CN'
6 , namespaces =>'default ''http://www.oracle.com/a.xsd'''
7 )
8 from dual;
DBMS_XMLSTORAGE_MANAGE.XPATH2T
<Result>
<Mapping TableName="SYS_NTr0U7dPWyRu6OVvDN2f5HEg==" ColumnName="CN"/>
</Result>
4) Creating the index :
SQL> create index CHANGE_HISTORY_IX1 on "SYS_NTr0U7dPWyRu6OVvDN2f5HEg==" ("CN");
Index created
If you're going to create multiple indexes like this, you could really benefit from renaming all the nested tables to meaningful names. That can be done via DBMS_XMLSTORAGE_MANAGE as well. -
Please can anyone help with ajax memory tree
I need to have the ajax memory tree expanded on page load. Can anyone please give me some ideas or piece of code. I have the tree working perfectly but only, the users have to click on the + sign to see the branches. This is from Scott Spendolini's example.
Thanks in advance,
SumaHi Suma,
I posted this on the other thread but if you haven't checked that, here is the code I use to simulate the first button click (in a PL/SQL region after the tree region)
declare
l_id number;
begin
select id into l_id from tree_view where pid is null;
htp.p('<script language="Javascript">var table = document.getElementsByName("level_1");
if (table.item(0).name = "level_1")
getTreeNode(table.item(0),'||l_id||');
</script>');
end;
Cheers,
Paul -
Help with displaying a tree...
Hello,
I created a window program that displays some data in a tree structure. I have two versions of the program. One that works and one that doesn't. The one that does, builds the tree in the constructor method of my window class, creates a scrollPane for it, and adds the scrollPane to the window. Again, this version displays the tree fine.
The second version, what I want to accomplish is load the tree when a button is pressed. When the button is pressed, I execute exactly the same steps that I do in the constructor but now these steps are in the actionPerformed method associated to the button. The thing is that the program does not display the tree. I have tried the repaint methods at the contentPane level, at the tree level, reloading the treeModel, but cannot get the tree to show. I would very appreciate any ideas on this...
Thanks
AntonioHey...
Thanks for the tip...that did the trick. What does the validate() method do exactly? The documentation doesn't say much....Thanks again...
Antonio -
How to extend breadth first Search for Binary Tree to any kind of Tree??
Dear Friends,
I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ie each node has more than 2 leaves such as 1, 2,3,4 or any,
I have following code to successfully apply for breadth first Search in Binary Tree as follows,
package a.border;
import java.util.ArrayList;
import java.util.LinkedList;
public class Tree
int root;
Tree left;
Tree right;
static ArrayList<Integer> list = new ArrayList<Integer>();
static ArrayList<Tree> treeList = new ArrayList<Tree>();
private static LinkedList<Tree> queue = new LinkedList<Tree>();
* @param root root value
* @param left left node
* @param right right node
public Tree(int root, Tree left, Tree right)
this.root = root;
this.left = left;
this.right = right;
/** Creates a new instance of Tree
* You really should know what this does...
* @param root
public Tree(int root)
this.root = root;
this.left = null;
this.right = null;
* Simply runs a basic left then right traversal.
public void basicTraversal()
//Check if we can go left
if (left != null)
left.basicTraversal();
//Add the root
list.add(root);
//Check if we can go right
if (right != null)
right.basicTraversal();
public ArrayList<Integer> getBreadthTraversal(ArrayList<Integer> list)
//Add the root to the arraylist, we know it is always the first entry.
list.add(root);
//Basically we add the first set of nodes into the queue for
//traversing.
//Query if left exists
if (left != null)
//Then add the node into the tree for traversing later
queue.add(left);
//Same for right
if (right != null)
queue.add(right);
//Then we call the traverse method to do the rest of the work
return traverse(list);
private ArrayList<Integer> traverse(ArrayList<Integer> list)
//Keep traversing until we run out of people
while (!queue.isEmpty())
Tree p = queue.remove();
//Check if it has any subnodes
if (p.left != null)
//Add the subnode to the back of the queue
queue.add(p.left);
//Same for left
if (p.right != null)
//Same here, no queue jumping!
queue.add(p.right);
//Append to the ArrayList
list.add(p.root);
//And return
return list;
* Makes a tree and runs some operations
* @param args
public static void main(String[] args)
* 4
* t = 2 6
* 1 3 5 7
Tree leaf6 = new Tree(1);
Tree leaf7 = new Tree(3);
Tree leaf8 = new Tree(5);
Tree leaf9 = new Tree(7);
Tree t4 = new Tree(2, leaf6, leaf7);
Tree t5 = new Tree(6, leaf8, leaf9);
Tree t = new Tree(4, t4, t5);
t.basicTraversal();
System.out.println("Here is basicTraversal ="+list.toString());
list.clear();
t.getBreadthTraversal(list);
System.out.println("getBreadthTraversal= " +list.toString());
list.clear();
}Can Guru help how to update to any kind of tree??
here this code is for the tree like:
* 4
* t = 2 6
* 1 3 5 7
*/But i hope the new code can handle tree like:
* 4
* / | \
* / | \
* t = 2 8 6
* / | \ | /| \
* 1 11 3 9 5 10 7
*/Thankssunnymanman wrote:
Dear Friends,
I am thinking a problem, How to extend breadth first Search for Binary Tree to any kind of Tree?? ...The answer is interfaces.
What do all trees have in common? And what do all nodes in trees have in common?
At least these things:
interface Tree<T> {
Node<T> getRoot();
interface Node<T> {
T getData();
List<Node<T>> getChildren();
}Now write concrete classes implementing these interfaces. Let's start with a binary tree (nodes should have comparable items) and an n-tree:
class BinaryTree<T extends Comparable<T>> implements Tree<T> {
protected BTNode<T> root;
public Node<T> getRoot() {
return root;
class BTNode<T> implements Node<T> {
private T data;
private Node<T> left, right;
public List<Node<T>> getChildren() {
List<Node<T>> children = new ArrayList<Node<T>>();
children.add(left);
children.add(right);
return children;
public T getData() {
return data;
class NTree<T> implements Tree<T> {
private NTNode<T> root;
public Node<T> getRoot() {
return root;
class NTNode<T> implements Node<T> {
private T data;
private List<Node<T>> children;
public List<Node<T>> getChildren() {
return children;
public T getData() {
return data;
}Now with these classes, you can wite a more generic traversal class. Of course, every traversal class (breath first, depth first) will also have something in common: they return a "path" of nodes (if the 'goal' node/data is found). So, you can write an interface like this:
interface Traverser<T> {
List<Node<T>> traverse(T goal, Tree<T> tree);
}And finally write an implementation for it:
class BreathFirst<T> implements Traverser<T> {
public List<Node<T>> traverse(T goal, Tree<T> tree) {
Node<T> start = tree.getRoot();
List<Node<T>> children = start.getChildren();
// your algorithm here
return null; // return your traversal
}... which can be used to traverse any tree! Here's a small demo of how to use it:
public class Test {
public static void main(String[] args) {
Tree<Integer> binTree = new BinaryTree<Integer>();
// populate your binTree
Tree<Integer> nTree = new NTree<Integer>();
// populate your nTree
Traverser<Integer> bfTraverser = new BreathFirst<Integer>();
// Look for integer 6 in binTree
System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, binTree));
// Look for integer 6 in nTree
System.out.println("bTree bfTraversal -> "+bfTraverser.traverse(6, nTree));
}Good luck! -
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++;
} -
Problem with binary tree please help
i am trying to make a binary tree but the problem is that when i print the data only the last value is printed i think i am moving my root. but dont know how to solve it please help me.
public void insert(String n)
// (void)
if (root == null)
System.out.println("Root is null");
TreeNode temp = new TreeNode(n);
System.out.println("\n\n\n\n"+temp.name+"\n\n\n\n\n");
root = rootTemp = temp;
else
System.out.println("Root is not null" +rootTemp.name);
insert(rootTemp, n);
private TreeNode insert(TreeNode v, String n) {
if (v == null)
return new TreeNode(n);
else
if (n.compareTo(v.name) < 0)
v.left = insert(v.left, n);
else
v.right = insert(v.right, n);
return v;
}Are you sure the problem is not in the printing code?
I can't see any obvious mistakes after a quick look... But if "root" is a reference to the root node, what is "rootTemp"? -
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();
} -
I'm having some problems with my program. It's a binary tree of names but they aren't organized in any particular order and names can repeat. I built the tree correctly but the problem comes in writing a method. I have to write method pathLength with parameters (Treenode, Person (object), and level (starts as 1) ) it returns the longest path from the TreeNode to the node containing the Person. My code seems to work for most of the names on the tree except for one or two and I can't see why. Here's my code:
public int pathLength(TreeNode t, String name, int level)
if(t==null)
return 0;
else if((name.equals(t.getValue())&&(t.getLeft()==null||t.getRight()==null)))
return level;
return max(pathLength(t.getLeft(),name,level+1),pathLength(t.getRight(),name,level+1));
max is a method that returns the larger of two integers (x,y)
next I have to write method rootPath with parameter (TreeNode) that returns the longest path from the root of the tree to a node containing the same as root.........this method I'm not even close on but I would have thought that all I needed to do for code was
public int rootPath(TreeNode t)
return pathLength(t,(String)t.getValue(),1);
so that it would go from t to another node with t's value.........maybe its because pathLength doesn't workand also another part of my program that i'm having trouble with is a different tree which has letters as leaves and null's as parents etc. To get to a letter u follow a code of 1's and 0's so 1110 would be left left left right and u'd get a letter.....i wrote the code that i'll get a code and i can find the letter but now i hafta make it go opposite so i type a letter and it gives the code
they provided me with the main code
public String wordToBits(String word)
String result="";
for(int k=0; k<word.length(); k++)
result+=wordToBitsHelper(word.substring(k,k+1),myRoot,"""");
return result;
i hafta write method private String wordToBitsHelper(String s, Treenode t, String pathSoFar)
and im really lost -
Succinct encoding for binary tree with n nodes...
How do I find all possible bit strings (Succinct encoding) for a binary tree with order n? Can anybody give me an algorithm?
I associate the order of a tree with some sort of a search or traversal. What do you mean by a "+tree with order n+"?
Could you perhaps give an example of what you're looking for? -
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. -
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
-
Impossible to send a mail with a message in HTML format
Hi I try to send a message in HTML format. Here is the code : public void sendMessage(String subject, String message, String to, String cc, String bcc) throws MessagingException { MimeMessage mimeMessage = mailSender.createMimeMessage()
-
Allow others to order iPhoto calendar via Apple Photos Services (or other)
I thought I saw this option somewhere, but I have an iPhoto calendar that I've printed through Apple Photo Services for myself. I now want to make that cal available for others to print without having to be involved in placing the order for them. Is
-
Does Leopard Server make user/email lists?
Hi, We presently use QuickMail server, mainly because it keeps a local user email list, and sends it to all users each time it's changed. So, the question is, does Leopard Server Mail admin have a feature like this? This will be a major factor in whe
-
How to resolve a "low level exception occurred in adobe player"?
Timeline now not playing back footage and preventing me from working. Im using an iMac, OSX Version 10.8.5. Processor 3.2GHz Intel core i5. 32GB RAM. All updates for premiere pro have been done and still the problem. Any help would be greatly appreci
-
Im familiar with Unity 3D which is 3D game engine for pc, mac, android, iphone and ipad platforms. Last year Microsoft said that they are not going to support native code on WP7. This was before Nokia. Now when this new deal came public is Nokia goin