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?
Similar Messages
-
I need to create a simple Queue class for Binary Tree Node. The class consist of only enqueue and dequeue, I cannot use the Collection Interface though. But I have no idea how to do it. Below is my Binary Tree Node Class.
public class BTNode {
private customer item;
private BTNode left;
private BTNode right;
public BTNode() {// constructor
item = null;
left = right = null;
public BTNode(customer newItem) {// constructor
item = newItem.clone();
left = right = null;
public void setItem(customer newItem) {// set methods
item = newItem.clone();
public void setLeft(BTNode newLeft) {
left = newLeft;
public void setRight(BTNode newRight) {
right = newRight;
public customer getItem() { // get methods
return item;
public BTNode getLeft() {
return left;
public BTNode getRight() {
return right;
public class Queue1 extends BTNode {
public Queue1() {
super();
public void enqueue(BTNode newItem) {
public void dequeue() {
}public class Queue1 extends BTNode {Why do you think that the queue should extend BTNode?
You probably want to aggregate a List.
Kaj -
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! -
How to design databse for binary tree
kindly help in desiging databse for binary tree and also to retrive data from database.
Since you're not asking about Java, you'll probably get more responses by posting this in a database forum.
-
Binary tree - a spesific node's height !
hello !
im looking for a method to deterine a certain node's hight in a binary tree (that is its distance from the root )
please enlighten me on how to do this if you can
thank you> Traverse the BT and with every step increase a
counter. When you get to the node you're looking for,
return the counter.
Or just add an attribute to you TreeNode class which holds the value for the degree/height of the node. -
Binary Tree: Number of Nodes at a Particular Level
Hi, I'm trying to teach myself about binary tree but am having trouble writing an algorithm. The algorithm that I'm trying to write is one that will take a binary tree and output the number of nodes at each level of the tree (maybe in an array).
I have no trouble writing an algorithm that does a breadth-first traversal, but I have lots of trouble trying to determine where each level ends.
Thanks for the helpTry something like this:
class BTree {
BTreeNode root;
public int numberOfNodesAtLevel(int level) {
if(root == null) return -1;
return numberOfNodesAtLevel(root, level);
private int numberOfNodesAtLevel(BTreeNode node, int level) {
if(level == 0) {
return 1;
} else {
return (node.left == null ? 0 : numberOfNodesAtLevel(node.left, level-1)) +
(node.right == null ? 0 : numberOfNodesAtLevel(node.right,level-1));
} -
Data plug-in for binary data with byte streams of variable length
Hi there,
I would like to write a data plug-in to read binary data from file and I'm using DIAdem 10.1.
Each data set in my file consists of binary data with a fixed structure (readable by using direct access channels) and of a byte stream of variable length. The variable length of each byte stream is coded in the fixed data part.
Can anyone tell me how my data plug-in must look like to read such kind of data files?
Many thanks in advance!
Kind regards,
StefanHi Brad,
thank you for the very quick response!
I forgot to mention, that the data in the byte stream can actually be ignored, it is no data to be evaluated in DIAdem (it is picture data and the picture size varies from data set to data set).
So basically, of each data set I would like to read the fixed-structure data (which is the first part of the data set) and discard the variable byte stream (last part of the data set).
Here is a logical (example) layout of my binary data file:
| fixedSize-Value1 | fixedSize-Value2 | fixedSize-Value3 (=length of byte stream) | XXXXXXXXXXXXX (byte stream)
| fixedSize-Value1 | fixedSize-Value2 | fixedSize-Value3 (=length of byte stream) | XXXXXX (byte stream)
| fixedSize-Value1 | fixedSize-Value2 | fixedSize-Value3 (=length of byte stream) | XXXXXXXXXXXXXXXXXXXX (byte stream)
What I would like to show in DIAdem is only fixedSize-Value1 and fixedSize-Value2.
´
If I understood right, would it be possible to set the BlockLength of each data set by assigning Block.BlockLength = fixedSize-Value3 and to use Direct Access Channels for reading fixedSize-Value1 and fixedSize-Value2 ?
Thank you!
Kind regards,
Stefan -
Help:UIModel.xml file for ADF Tree with three level depth
Hello,
I am trying to create a DCTree with structure like this:
root....branch1----child11,child12
..........branch2......branch21---child212,child212
............................branch22---child221,child222
Because I can not create more than one binding rule due to the problem that "Add New Rule" button disappears after the first rule is created when I use the tool under Createbinding/Input/Tree to create the DCTree.
Could somebody post or send me a script of the UIModel.xml file of the tree structure above so that I can work around this problem?
Thanks in advance,
DeborahHi,
I haven't test it for more than 3 layers but I have never seen this limitation mantioned anywhere.
I used HGrid and this is my code:
1. UIX file (the relevant part highlighted):
<?xml version = '1.0' encoding = 'windows-1252'?>
<page xmlns="http://xmlns.oracle.com/uix/controller"
xmlns:ui="http://xmlns.oracle.com/uix/ui"
xmlns:data="http://xmlns.oracle.com/uix/ui"
xmlns:ctrl="http://xmlns.oracle.com/uix/controller"
xmlns:html="http://www.w3.org/TR/REC-html40" expressionLanguage="el"
xmlns:myTemplate="test">
<templates xmlns="http://xmlns.oracle.com/uix/ui">
<templateImport source="baseTemplate.uit"/>
</templates>
<content>
<dataScope xmlns="http://xmlns.oracle.com/uix/ui">
<provider>
<!-- Add DataProviders (<data> elements) here -->
</provider>
<contents>
<document>
<metaContainer>
<!-- Set the page title -->
<head title=""/>
</metaContainer>
<contents>
<body>
<contents>
<form name="form0">
<contents>
<myTemplate:baseTmpl title="" xmlns:myTemplate="test">
<contents>
<rowLayout>
<contents>
<link text="Bets View" destination="browseCustBets.do"/>
<spacer width="10" height="10"/>
<link text="Customer Bets" destination="viewCustBets.do"/>
</contents>
</rowLayout>
<rowLayout>
<contents>
<spacer width="10" height="10"/>
</contents>
</rowLayout>
<rowLayout>
<contents>
<hGrid id="hg1" treeData="${uix.data.treeData}" proxy="${uix.eventResult.hGridProxy}">
<columnHeaderData>
<col text="Email"/>
<col text="Bet Date"/>
<col text="ID"/>
<col text="Is Winner"/>
<col text="Amount"/>
<col text="Rate"/>
</columnHeaderData>
<columnHeaderStamp>
<text text="${uix.current.text}"/>
</columnHeaderStamp>
<columnFormats>
<columnFormat columnDataFormat="textFormat" width="140"/>
<columnFormat columnDataFormat="textFormat" width="160"/>
<columnFormat columnDataFormat="textFormat" width="40"/>
<columnFormat columnDataFormat="textFormat" width="70"/>
<columnFormat columnDataFormat="textFormat" width="70"/>
<columnFormat columnDataFormat="textFormat" width="40"/>
</columnFormats>
<contents>
<text text="${uix.current.Email}"/>
<text text="${uix.current.BetDate}"/>
<text text="${uix.current.BetID}"/>
<text text="${uix.current.IsWinner}"/>
<text text="${uix.current.Amount}"/>
<text text="${uix.current.Rate}"/>
</contents>
</hGrid>
</contents>
</rowLayout>
</contents>
<tabs/>
<pageButtons/>
<globalButtons/>
<pageHeader/>
<start/>
<end/>
<about/>
<copyright/>
<privacy/>
<corporateBranding/>
<productBranding/>
</myTemplate:baseTmpl>
<formValue name="${bindings.statetokenid}" value="${bindings.statetoken}" id="_uixState"/>
</contents>
</form>
</contents>
</body>
</contents>
</document>
</contents>
<provider>
<data name="treeData">
<method class="view.CreateTreeData" method="getTreeData"/>
</data>
</provider>
</dataScope>
</content>
<handlers>
<event name="*">
<method class="view.BetDetailsAction" method="doHGridEvent"/>
</event>
</handlers>
</page>
2. CreateTreeData class:
It has a static method getTreeData() that returns a DataObject containing the tree nodes. This methode is mentiond in <provider> node in UIX/XML.
package view;
import java.util.Enumeration;
import model.*;
import oracle.cabo.servlet.BajaContext;
import oracle.cabo.servlet.ServletConstants;
import oracle.cabo.servlet.ui.BajaRenderingContext;
import oracle.cabo.ui.RenderingContext;
import oracle.cabo.ui.UIConstants;
import oracle.cabo.ui.data.DataObject;
import oracle.cabo.ui.data.servlet.HttpSessionDataObject;
import oracle.cabo.ui.data.tree.SimpleTreeData;
import oracle.jbo.ApplicationModule;
import oracle.jbo.ViewObject;
import oracle.adf.model.BindingContext;
import oracle.adf.model.binding.DCDataControl;
//import oracle.jbo.common.Configuration;
import javax.servlet.http.HttpSession;
import oracle.jbo.client.Configuration;
public class CreateTreeData
public CreateTreeData()
public static DataObject getTreeData(RenderingContext context, String namespace, String name)
// create root node
SimpleTreeData root = new SimpleTreeData();
int BetID = 0;
// get the parameter from url
BajaContext bContext = (BajaContext) context.getProperty(ServletConstants.BAJA_NAMESPACE,
BajaRenderingContext.BAJA_CONTEXT_PROPERTY);
HttpSession session = bContext.getServletRequest().getSession(true);
try
//BetID = new Integer(( bContext.getServletRequest( ) ).getParameter( "BetID" )).intValue();
String s = ( bContext.getServletRequest( ) ).getQueryString();
BetID = new Integer(s).intValue();
session.setAttribute("BetID", s);
//BetID = new Integer(session.getAttribute("BetID").toString()).intValue();
catch ( Exception ex)
// log the error on the console
BetID = new Integer(session.getAttribute("BetID").toString()).intValue();
//System.out.println( "Parameters cannot be retrieved" );
//System.out.println( ex.getMessage() );
String amDef = "model.AppModule";
String config = "AppModuleLocal";
ApplicationModule am = Configuration.createRootApplicationModule(amDef, config);
AppModuleImpl myAm = (AppModuleImpl)am;
root = myAm.createNodesData(BetID);
myAm.remove();
Configuration.releaseRootApplicationModule(am,true);
// return the tree
return root;
3. createNodesData(int Id) is the actual function that creates the data structure containing the nodes.
It is in AppModule. The actual tree is kept in one table and every node knows its parent ID. There is no limitation in depth.
This function is called recursively until the tree is finished and the parameter Id is the Id of the parent node that I want to be listed. Tne top parent nodes has null in ParentID field.
public SimpleTreeData createNodesData(int Id)
SimpleTreeData tData = new SimpleTreeData();
String baseSQL =
"SELECT Bet.ID, Bet.CUST_LOGIN_ID, Bet.BET_CLASS_ID, Bet.PARENT_BET_ID," +
"Bet.CHAMPIONSHIP_ID, Bet.AMOUNT, Bet.WIN_RATE, Bet.IS_WINNER, Bet.BET_DATE, " +
"BetClass.NAME, CustLogin.EMAIL, CustLogin.ID AS CUST_LOGIN_ID " +
"FROM BET Bet, CUST_LOGIN CustLogin, BET_CLASS BetClass " +
"WHERE (Bet.CUST_LOGIN_ID = CustLogin.ID) AND (Bet.BET_CLASS_ID = BetClass.ID) ";
if(Id!=0){
String sqlStmt = baseSQL + " AND (Bet.ID = '"+ Id +"')";
ViewObject betVo = this.createViewObjectFromQueryStmt("betVo", sqlStmt);
betVo.executeQuery();
if(betVo.hasNext())
//SimpleTreeData tData = new SimpleTreeData();
tData.setText(betVo.first().getAttribute("NAME").toString());
if(betVo.first().getAttribute("PARENT_BET_ID")==null)
tData.put("Email", betVo.first().getAttribute("EMAIL").toString());
tData.put("BetDate", betVo.first().getAttribute("BET_DATE").toString());
tData.put("BetID", betVo.first().getAttribute("ID").toString());
tData.put("IsWinner", betVo.first().getAttribute("IS_WINNER").toString());
tData.put("Amount", betVo.first().getAttribute("AMOUNT").toString());
tData.put("Rate", betVo.first().getAttribute("WIN_RATE").toString());
if(Integer.parseInt(betVo.first().getAttribute("BET_CLASS_ID").toString())>1){
tData.setExpandable(UIConstants.EXPANDABLE_EXPANDED);
betVo.remove();
String sqlStmt = baseSQL + " AND (Bet.PARENT_BET_ID = '"+ Id +"')";
ViewObject betVo = this.createViewObjectFromQueryStmt("betVo" + Id, sqlStmt);
betVo.executeQuery();
while(betVo.hasNext()){
tData.addChild(createNodesData(Integer.parseInt(betVo.next().getAttribute("ID").toString())));
betVo.remove();
return tData;
Hope this will help... -
Hierarchical tree with iconic nodes
hi i'm using database - 10g, developer suite - 10g; created a hierarchical tree and the icons are displaying along side the nodes when they are being selected or activated.
problem - i've stored the icons in g:\ICONS (all gif icons). but when i run the form it is picking up the icons from the following location - C:\Documents and Settings\development\Oracle Jar Cache\frmall_jinit.jar-63ace618-1160d49b\oracle\forms\icons. I've a button in the same form and the icon showing on it is from the location G:\ICONS(as desired); but in case of tree it's from the location which is not desirable.
any help.Hello,
You need to change the imagebase parameter to be documentbase instead of codebase.
When imagebase is set to codebase forms looks for Images in the jar files and then in the absolute path, otherwise it check direct path.
For details in deploying the Images please check:
http://docs.oracle.com/cd/B14099_19/web.1012/b14032/configure009.htm
Clear the Java cache and browser cache after the above changes!
Regards,
Alex
If someone's answer is helpful or correct please mark it accordingly! -
How to use For-Each Structure with Multiple node XML structure
Hi,
How to use for-each (BPEL 2.0) construct for Multinode XML structure.
Here is the easy case: I have list of suppliers specified by supplier
<supplierList>
<supplier>1</supplier>
<supplier>2</supplier>
<supplier>3</supplier>
</supplierList>
Now there is a web service http://hostname/getsupplierdetails/wsdl which accepts one supplier at a time.
like
<supplier>1</supplier>
reponse object is
<message> notfound/found </message>
But how can I use for each of XML node to call this service and collect the result like
<supplierList1>
<Suppinfo>
<supplier>1</supplier>
<message> not found</message>
</suppinfo>
<suppinfo>
<supplier>1</supplier>
<message> not found</message>
</suppinfo>
</supplierlist1>
ThanksFor looping you use foreach loop and , loop for the number of occurences and when constructing response, adding a new element you have to use bpelx:append. Good sample at Enterprise Integration: Oracle SOA Suite 11g: Populating a list or an array in BPEL without using XSLT.
-
How to remember the path while traverse a binary tree?
Hi, again, I have difficulty handling tree search problems.
The quesion is How to search for a node from a binary tree A, return true if found meanwhile generate the path which can be used to locate the node.
I think the signature should be:
// The path contains only 0s and 1s. 0 means go left and 1 means go right.
public staic boolean search(Node rootOfA, Node b, ArrayList<Integer> path){
// the class Node only has two fields:
Node{
Node left;
Node right;
I know if there is another field in the Node class (say, a flag), the quesion would be much easier, but the space is really critical.
I tried to use recursion but havn't got a correct solution. I am thinking of usinga non-recursion algo.
Anyone wants to help?Hi, JosAh,
That's mind provoking. However, I do think it works. It does not pop some stuff it should pop. I tested it over a very simple tree and it failed. Did you test it? I might be wrong...
The tree I am working on does not have null pointers, the condition to test if a node is a leaf is if(node.right == right). Namly, all the right pointer of leaves points to itself.
So I changed your code to be:
Stack search(Node root, Node node, Stack<Integer> path) {
if (root == null || root.right ==right) return null;
if (root.equals(node)) return path;
path.push(0);
if (search(root.left, node, path) != null) return path;
path.pop();
path.push(1);
return search(root.right, node, path);
}I simply tested it with
Stack<Integer> path = new Stack<Integer>();
System.out.println( root, root.right.right, path);
root is the root of a complete binary tree with 7 nodes(4 leaves).
Apparenly, if the path is built correctly search(root, root.right.right, path) would return [1,1] whereas this seach returns [ 0 , 1, 1].
Considerring , the right branch never pops, I changed it into
Then I changed it to :
Stack search(Node root, Node node, Stack<Integer> path) {
if (root == null || root.right ==right ) return null;
if (root.equals(node)) return path;
path.push(0);
if (search(root.left, node, path) != null) return path;
path.pop();
path.push(1);
if (search(root.right, node, path) != null) return path;
path.pop();
return path;
With the same test case, it returns [].
I will keep working on it.
Cheers,
Message was edited by:
since81
Message was edited by:
since81 -
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++;
} -
So I have an assignment to write a program that deciefers basic morse code using a binary tree. A file was provided with the information for the binary tree and I am using the text books author's version of BinaryTree class with a few methods of my own thrown in.
For starters .. why would you ever use a tree for this .. just make a look up table. But my real problem is i keep getting null pointers at 38, 24, 55 and I have tried just about everything I know to do at this point. My mind is exhausted and I think I need a fresh pair of eyes to tell me what I have done wrong.
I am sorry for such sloppy code.. I have been changing and rearranging too much.
import java.io.*;
import java.util.*;
public class MorseCode extends BinaryTree{
static BufferedReader in;
static BinaryTree<String> bT = new BinaryTree<String>();
/* public static void loadTree() throws FileNotFoundException, IOException{
in = new BufferedReader(new FileReader("MorseCode.txt"));
bT = readBinaryTree(in);
public static String decode(Character c) throws IOException{
if(c.equals("null")){
return "";
}else if(c.equals(" ")){
return " ";
}else{
return (":" + find(c));
public static String find(Character c) throws IOException, FileNotFoundException{
in = new BufferedReader(new FileReader("MorseCode.txt"));
bT = readBinaryTree(in);
Queue<BinaryTree> data = new LinkedList<BinaryTree>();
BinaryTree<String> tempTree = bT;
String temp = null;
Character tempChar = null;
data.offer(tempTree);
while(!data.isEmpty()){
tempTree = data.poll();
temp = tempTree.getData();
tempChar = temp.charAt(0);
if(tempChar.equals(c)){
break;
data.offer(tempTree.getRightSubtree());
data.offer(tempTree.getLeftSubtree());
return temp.substring(2);
public static void main(String[] args) throws FileNotFoundException, IOException{
Scanner scan = new Scanner(new FileReader("encode.in.txt"));
String s = "";
String temp = "";
while(scan.hasNextLine()){
temp = scan.nextLine();
for(int i = 0; i < temp.length(); i++){
s = s + decode(temp.charAt(i));
System.out.println(s);
/** Class for a binary tree that stores type E objects.
* @author Koffman and Wolfgang
class BinaryTree <E> implements Serializable
//===================================================
/** Class to encapsulate a tree node. */
protected static class Node <E> implements Serializable
// Data Fields
/** The information stored in this node. */
protected E data;
/** Reference to the left child. */
protected Node <E> left;
/** Reference to the right child. */
protected Node <E> right;
// Constructors
/** Construct a node with given data and no children.
@param data The data to store in this node
public Node(E data) {
this.data = data;
left = null;
right = null;
// Methods
/** Return a string representation of the node.
@return A string representation of the data fields
public String toString() {
return data.toString();
}//end inner class Node
//===================================================
// Data Field
/** The root of the binary tree */
protected Node <E> root;
public BinaryTree()
root = null;
protected BinaryTree(Node <E> root)
this.root = root;
/** Constructs a new binary tree with data in its root,leftTree
as its left subtree and rightTree as its right subtree.
public BinaryTree(E data, BinaryTree <E> leftTree, BinaryTree <E> rightTree)
root = new Node <E> (data);
if (leftTree != null) {
root.left = leftTree.root;
else {
root.left = null;
if (rightTree != null) {
root.right = rightTree.root;
else {
root.right = null;
/** Return the left subtree.
@return The left subtree or null if either the root or
the left subtree is null
public BinaryTree <E> getLeftSubtree() {
if (root != null && root.left != null) {
return new BinaryTree <E> (root.left);
else {
return null;
/** Return the right sub-tree
@return the right sub-tree or
null if either the root or the
right subtree is null.
public BinaryTree<E> getRightSubtree() {
if (root != null && root.right != null) {
return new BinaryTree<E>(root.right);
} else {
return null;
public String getData(){
if(root.data == null){
return "null";
}else{
return (String) root.data;
/** Determine whether this tree is a leaf.
@return true if the root has no children
public boolean isLeaf() {
return (root.left == null && root.right == null);
public String toString() {
StringBuilder sb = new StringBuilder();
preOrderTraverse(root, 1, sb);
return sb.toString();
/** Perform a preorder traversal.
@param node The local root
@param depth The depth
@param sb The string buffer to save the output
private void preOrderTraverse(Node <E> node, int depth,
StringBuilder sb) {
for (int i = 1; i < depth; i++) {
sb.append(" ");
if (node == null) {
sb.append("null\n");
else {
sb.append(node.toString());
sb.append("\n");
preOrderTraverse(node.left, depth + 1, sb);
preOrderTraverse(node.right, depth + 1, sb);
/** Method to read a binary tree.
pre: The input consists of a preorder traversal
of the binary tree. The line "null" indicates a null tree.
@param bR The input file
@return The binary tree
@throws IOException If there is an input error
public static BinaryTree<String> readBinaryTree(BufferedReader bR) throws IOException
// Read a line and trim leading and trailing spaces.
String data = bR.readLine().trim();
if (data.equals("null")) {
return null;
else {
BinaryTree < String > leftTree = readBinaryTree(bR);
BinaryTree < String > rightTree = readBinaryTree(bR);
return new BinaryTree < String > (data, leftTree, rightTree);
}//readBinaryTree()
/*Method to determine the height of a binary tree
pre: The line "null" indicates a null tree.
@param T The binary tree
@return The height as integer
public static int height(BinaryTree T){
if(T == null){
return 0;
}else{
return 1 +(int) (Math.max(height(T.getRightSubtree()), height(T.getLeftSubtree())));
public static String preOrderTraversal(BinaryTree<String> T){
String s = T.toString();
String s2 = "";
String temp = "";
Scanner scan = new Scanner(s);
while(scan.hasNextLine()){
temp = scan.nextLine().trim();
if(temp.equals("null")){
s2 = s2;
}else{
s2 = s2 + " " + temp;
return s2;
}//class BinaryTreeAs well as warnerja's point, you say you keep getting these errors. Sometimes it's helpful when illustrating a problem to replace the file based input with input that comes from a given String. That way we all see the same behaviour under the same circumstances.
public static void main(String[] args) throws FileNotFoundException, IOException{
//Scanner scan = new Scanner(new FileReader("encode.in.txt"));
Scanner scan = new Scanner("whatever");The following isn't the cause of an NPE, but it might be allowing one to "slip through" (ie you think you've dealt with the null case when you haven't):
public static String decode(Character c) throws IOException{
if(c.equals("null")){
c is a Character so it will never be the case that it is equal to the string n-u-l-l.
Perhaps the behaviour of each of these methods needs to be (documented and) tested. -
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();
} -
Ok people I need help!
I want to create, from a pre-order and in-order sequences, the post-order sequence! Obviously there are no repeated elements (characters from A to Z at this case).
The tree root it's the first character from pre-order and after that it's easy to take left and right sequences.
I found an interesting explanation: http://www.dcs.kcl.ac.uk/staff/pinz...st/html/l7.html
I've tried everything to make it recursive I think that's the best way to do it but somehow I can't make it work! My last code:
import java.io.*;
import java.util.*;
public class Problem
static String readLn (int maxLg) // utility function to read from stdin
byte lin[] = new byte [maxLg];
int lg = 0, car = -1;
try
while (lg < maxLg)
car = System.in.read();
if ((car < 0) || (car == '\n')) break;
lin [lg++] += car;
catch (IOException e)
return (null);
if ((car < 0) && (lg == 0)) return (null); // eof
return (new String (lin, 0, lg));
public static void main (String []args)
for (int set = Integer.parseInt(readLn(10).trim()); set != 0; set--)
StringTokenizer tok = new StringTokenizer(readLn(100).trim()," ");
String preOrd = tok.nextToken();
String inOrd = tok.nextToken();
char root = preOrd.charAt(0);
BinaryNode tree = new BinaryNode(root);
// Left and right from inOrd
tok = new StringTokenizer(inOrd,Character.toString(root));
String inOrdLeft = tok.nextToken();
String inOrdRight = tok.nextToken();
// Take left and right from preOrd
String preOrdLeft = preOrd.substring(1,inOrdLeft.length()+1);
String preOrdRight = preOrd.substring(inOrdLeft.length()+1);
tree.left = work (preOrdLeft, 0, inOrdLeft);
tree.right = work (preOrdRight, 0, inOrdRight);
tree.printPostOrder();
System.out.println();
public static BinaryNode work (String preOrd, int preOrdPoint, String inOrd)
char nodeChr = preOrd.charAt(preOrdPoint);
String nodeStr = Character.toString(nodeChr);
//System.out.println("Root: "+nodeStr+" preOrd: "+preOrd+" inOrd: "+inOrd);
BinaryNode tempTree = new BinaryNode(nodeChr);
StringTokenizer tok = new StringTokenizer(inOrd,nodeStr);
try
String newInOrdLeft = tok.nextToken();
if (newInOrdLeft.length() == 1) { tempTree.left = new BinaryNode(newInOrdLeft.toCharArray()[0]); }
else if (newInOrdLeft.length() != 0) { tempTree.left = work(preOrd, preOrdPoint+1, newInOrdLeft); }
catch (NoSuchElementException e) {}
try
String newInOrdRight = tok.nextToken();
if (newInOrdRight.length() == 1) { tempTree.right = new BinaryNode(newInOrdRight.toCharArray()[0]); }
else if (newInOrdRight.length() != 0) { tempTree.right = work(preOrd, preOrdPoint+1, newInOrdRight); }
catch (NoSuchElementException e) {}
return tempTree;
class BinaryNode
char chr;
BinaryNode left = null;
BinaryNode right = null;
BinaryNode()
BinaryNode(char c)
this(c, null, null);
BinaryNode(char c, BinaryNode lt, BinaryNode rt)
chr = c;
left = lt;
right = rt;
static int size(BinaryNode t)
if (t == null) { return 0; }
else { return size(t.left) + 1 + size(t.right); }
static int height(BinaryNode t)
if (t == null) { return 0; }
else { return 1 + Math.max(BinaryNode.height(t.left), BinaryNode.height(t.right)); }
void printPostOrder () {
if( left != null )
left.printPostOrder( ); // Left
if( right != null )
right.printPostOrder( ); // Right
System.out.print(chr); // Node
static BinaryNode insert (char c, BinaryNode t)
Character tmp = new Character(c);
if (t == null)
t = new BinaryNode(c, null, null);
else if (tmp.compareTo(new Character(t.chr)) < 0)
t.left = insert(c, t.left );
else if (tmp.compareTo(new Character(t.chr)) > 0)
t.right = insert(c, t.right);
return t;
}I don't know if this is a translation of your C code, but it can reconstruct any binary tree (with letters as nodes and no duplicates) from preorder and inorder traversals. Hope it helps.
import java.util.*;
public class ReconstructTree {
public ReconstructTree() {
public static void main(String[] args)
String preorder = "ABDGKLRVWSXCEHMNFIOTUJPYQZ";
String inorder = "KGVRWLSXDBAMHNECTOUIFPYJZQ";
Map table = new HashMap();
Map table2 = new HashMap();
for(int i=0; i<inorder.length(); i++)
table.put("" + inorder.charAt(i), new Integer(i));
table2.put(new Integer(i), "" + inorder.charAt(i));
List temppreorder = new ArrayList();
for(int i=0; i<preorder.length(); i++)
temppreorder.add(table.get("" + preorder.charAt(i)));
Node root = constructTree(temppreorder);
printPostOrder(root, table2);
public static void printPostOrder(Node root, Map table)
if(root == null)
return;
Node left = root.getLeft();
Node right = root.getRight();
printPostOrder(left, table);
printPostOrder(right, table);
System.out.print(table.get(new Integer(Integer.parseInt("" + root.getValue()))));
public static Node constructTree(List preorder)
Iterator it = preorder.iterator();
int r = ((Integer)it.next()).intValue();
Node root = new Node(r);
Node node = root;
while(it.hasNext())
node = root;
int a = ((Integer)it.next()).intValue();
while(true)
r = node.getValue();
if(a < r)
if(node.getLeft() == null)
node.setLeft(new Node(a));
break;
else
node = node.getLeft();
else
if(node.getRight() == null)
node.setRight(new Node(a));
break;
else
node = node.getRight();
return root;
public static class Node
private Node left = null;
private Node right = null;
private int value;
public Node(int v)
value = v;
public int getValue()
return value;
public Node getLeft()
return left;
public Node getRight()
return right;
public void setLeft(Node l)
left = l;
public void setRight(Node r)
right = r;
}
Maybe you are looking for
-
I's trying to connect my macbook pro to my pc so i can share files but i cant figure out how
i tried to connect my macbook to the pc through workgroup, but when i pressed on it it dissapeared. I cant figure out how to connect my macbook, to my Pc to share files.
-
Data mining Algorithms in Essbase
Hi, Just wondering if anyone has used data mining algorithms provided within Essbase. Any thoughts or pointers towards more information will be helpful.. Thanks in Advance !!
-
Module changes in SAP from GAAP to IFRS
Hi, I would like to know from you IFRS experts with SAP if you could please tell me the following What are actual changes within SAP modules FI, MM, PP, CO SD from GAAP to IFRS? In addition, what are the actual physical field or option changes that w
-
I can barely hear my ringer or Siri with my volume set all the way up.
I can barely hear my ringer and it's turned all the way up. I can't hear Siri at all but I can visually see that it's working. The ringer is completely silent when I turn the volume down two bars.
-
Hi All, I am having below subroutine and need to find the program to which it belongs. Can anyone please help me. PERFORM USER_EXIT_010 TABLES AS_BKPF AS_BSEG USING AS_MESTYP