Namespace, IXpathFunction "tree" return

I am trying to implement an IXpathFunction component. My Java runs fine but I am having trouble getting the data back into my BPEL process in a usable way.
So far I have 3 User Defined Functions. 2 of them I can read from just fine but one of them is giving me fits.
My returns for these are:
String (base64 encoded binary actually... but that's just a big string)
tree -- <caseNumber resultString=" " status=" " messageOut=" "/>
When I check the flow trace I see this in the update:
<caseNumberEdit xmlns="http://xmlns.oracle.com/f17userDefinedFunctions" resultString="011-4563457" status="0" messageOut="Success"/>
tree -- <sortList xmlns:f17="http://entp.hud.gov/f17UserDefinedFunctions"><f17:sortedCollection><f17:item></f17:item></f17:sortedCollection></sortList>
When I check the flow trace I see this i the update:
<sortedCollection xmlns="http://xmlns.oracle.com/f17userDefinedFunctions"><item xmlns="">134</item><item xmlns="">34555</item><item xmlns="">35345</item><item xmlns="">555134</item></sortedCollection>
So.... What's the deal? My Java program doesn't send that text: it sends:
<sortList xmlns:f17="http://xmlns.oracle.com/f17userDefinedFunctions">
<sortedCollection>
<f17:item>134<f17:item>
<f17:item>34555</f17:item>
<f17:item>35345</f17:item>
<f17:item>555134</f17:item>
</f17:sortedCollection>
</sortList>
I create a variable based on "sortedCollection" and use the following statement to run my function and move the data to that variable:
(I have already moved data to each element in "$sortBuffer" prior to this copy statement)
<copy ignoreMissingFromData="yes" bpelx:insertMissingToData="yes">
        <from>oraext:parseEscapedXML(f17:sortList(ora:getContentAsString($sortBuffer)))</from>
        <to>$sortBuffer</to>
</copy>
I can see that my Java class read the input and did its job (sorted the items numerically) and that the sorted data was returned but even though $sortBuffer
has been populated I can't read the data. Each of the nodes defined in the schema evaluate as empty.
Here is the schema for these objects:
<?xml version="1.0" encoding="windows-1252" ?>
<schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
            xmlns:f17="http://www.w3.org/2001/XMLSchema"
            xmlns="http://www.w3.org/2001/XMLSchema"
            targetNamespace="http://xmlns.oracle.com/f17userDefinedFunctions"
            elementFormDefault="qualified">
        <f17:element name="caseNumberEdit" >
            <f17:complexType>
                <f17:attribute name="resultString" type="f17:string"/>
                <f17:attribute name="status" type="f17:int"/>
                <f17:attribute name="messageOut" type="f17:string"/>
            </f17:complexType>
        </f17:element>
        <f17:element name="sortedCollection" >
            <f17:complexType>
                <f17:sequence>
                    <f17:element name="sortlist">
                        <f17:complexType>
                            <f17:sequence>
                                <f17:element name="item" type="string" minOccurs="0" maxOccurs="unbounded"/>
                            </f17:sequence>
                        </f17:complexType>
                    </f17:element>
                </f17:sequence>
            </f17:complexType>
        </f17:element>
</schema>

Yes sure.
I have a plsql region which calls a procedure and in that procedure I have a cursor which selects values from a table with a hierarchical structure (self referencing). At the moment I pass in a start value and generate the values in the cursor using a tree walk.
What I would like to do is present my hierarchical structure in tree report on screen and then somehow pass the values displayed on the screen into my procedure.
I could write my own tree report that is based on a collection and every time a node is opened I would update the collection with the child node values etc. I could then use the collection in my plsql procedure. However, producing a tree report by hand will be a bit of work, so I was wondering what was available out of the box, or if someone had already done it.
I hope this clear and please don’t ask me to reproduce it on apex.oracle.com :-)
Shunt

Similar Messages

  • Column Tree: returning to selection screen

    Guys,
    In a moment of pure genious I've created a work-of-art with column-trees. The report works great - except for one little problem....
    I can't seem to get back to the selection-screen without loosing the original selection-screen values.
    I've tried heaps of things without luck:
    set screen 0, leave screen
    call selection screen 1000
    call transaction ....
    leave program
    leave program to screen 0
    Any better ideas?

    From the SAP documentation :
    >>
    Ends current processing and starts the (new) transaction tcod. All previous internal sessions are deleted from the stack and one new internal session is opened for the program of the transaction that was called. When this session has finished, the system returns to the next higher area menu.
    <<
    If you close the session, you will loose all the memory, so all the parameters that is not in the memory with a SET PARAMETER ID ...
    Fred

  • 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,
    Deborah

    Hi,
    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...

  • Problem with trees(Duplication of the parent node in creation of  children)

    Hi guys i am experiencing a slight problem with the creation of trees.Here is a clear explanation of my program.I created a program that generates edges from a set of datapoints then use each and every edge that is generated to create multiple trees with the edge as the rootnode for each and every tree.Everything up to so far everything went well but the problem comes when i want the program to pick every single tree and traverse through the set of generated edges to create the children of a tree.What it does at the moment for each tree is returning the a duplication of the parent node as the child nodes and that is a problem.Can anyone related with this problem help.Your help will be appreciated.
    The code
    TreeNode class
    package SPO;
    import java.util.*;
    public class TreeNode
            Edge edge;
            TreeNode node;
         Vector childrens = new Vector();
            public TreeNode(Edge edge)
                    this.edge = edge;
            public synchronized  void insert(Edge edge)
                    if(edge.fromNode == this.edge.toNode)
                            if(node == null )
                                    node = new TreeNode(edge);
                                    childrens.add(node);
                            else
                        node.insert(edge);
                                    childrens.add(node);
    Tree class
    package SPO;
    import java.util.*;
    public class Tree
            TreeNode rootNode;
         public Tree()
                    rootNode = null;
            public Tree[]  createTrees(Vector initTrees,Vector edges)
                   Tree [] trees =  new Tree[initTrees.size()];
                   for(int c = 0;c < trees.length;c++)
                      trees[c] = (Tree)initTrees.elementAt(c);     
                   for(int i = 0;i < trees.length;i++)
                            for(int x = 0;x < edges.size();x++)
                                    Vector temp = (Vector)edges.elementAt(x);
                                    for(int y = 0;y < temp.size();y++)
                                           trees.insertNode((Edge)temp.elementAt(y));
    return trees;
    public void printTree(Tree tree)
    System.out.print("("+tree.rootNode.edge.fromNode.getObjName()+","+tree.rootNode.edge.toNode.getObjName()+")");
    Vector siblings = tree.rootNode.childrens;
    for(int i = 0; i < siblings.size();i++)
    TreeNode node = (TreeNode)siblings.elementAt(i);
    System.out.print("("+node.edge.fromNode.getObjName()+","+node.edge.toNode.getObjName()+")");
    System.out.println();
    public Vector initializeTrees(Vector edges)
    Vector trees = new Vector();
    for(int i = 0;i < edges.size();i++)
    Vector temp = (Vector)edges.elementAt(i);
    for(int j = 0;j < temp.size();j++)
    Tree tree = new Tree();
    tree.insertNode((Edge)temp.elementAt(j));
    trees.add(tree);
    return trees;
    public synchronized void insertNode(Edge edge)
    if(rootNode == null)
    rootNode = new TreeNode(edge);
    else
    rootNode.insert(edge);
    EdgeGenerator class
    package SPO;
    import java.util.*;
    import k_means.*;
    public class EdgeGenerator
         public EdgeGenerator()
    public Vector createEdges(Vector dataPoints)
    //OrderPair orderPair = new OrderPair();
    Vector edges = new Vector();
    for(int i = 0;i < dataPoints.size()-1 ;i++)
    Vector temp = new Vector();
    for(int j = i+1;j < dataPoints.size();j++)
    //Create an order of edges
    Edge edge = new Edge((DataPoint)dataPoints.elementAt(i),(DataPoint)dataPoints.elementAt(j));
    temp.add(edge);
    edges.add(temp);
    return edges;
    Edge class
    package SPO;
    import k_means.*;
    public class Edge
    public DataPoint toNode;
    public DataPoint fromNode;
    public Edge(DataPoint x,DataPoint y)
    if (x.getX() > y.getX())
    this.fromNode = x;
    this.toNode = y;
    else
    this.fromNode=y;
    this.toNode = x;
    Entry Point
    package SPO;
    import java.util.*;
    import k_means.*;
    public class Tester {
         public static void main(String[] args)
              Vector dataPoints = new Vector();
              dataPoints.add(new DataPoint(140, "Orange"));
              dataPoints.add(new DataPoint(114.2, "Lemmon"));
              dataPoints.add(new DataPoint(111.5, "Coke"));
              dataPoints.add(new DataPoint(104.6, "Pine apple"));
              dataPoints.add(new DataPoint(94.1, "W grape"));
              dataPoints.add(new DataPoint(85.2, "Appletizer"));
              dataPoints.add(new DataPoint(84.8, "R Grape"));
              dataPoints.add(new DataPoint(74.2, "Sprite"));
              dataPoints.add(new DataPoint(69.2, "Granadilla"));
              dataPoints.add(new DataPoint(59, "Strawbery"));
              dataPoints.add(new DataPoint(45.5, "Stone"));
              dataPoints.add(new DataPoint(36.3, "Yam"));
              dataPoints.add(new DataPoint(27, "Cocoa"));
              dataPoints.add(new DataPoint(13.8, "Pawpaw"));
    EdgeGenerator eg = new EdgeGenerator();
    Vector edges = eg.createEdges(dataPoints);
    Tree treeMaker = new Tree();
    Vector partialTrees = treeMaker.initializeTrees(edges);
    Tree [] trees = treeMaker.createTrees(partialTrees,edges);
    for(int i = 0;i < trees.length;i++)
    treeMaker.printTree(trees[i]);
    The program output
    Each and every "@" symbol represents the start of a tree
    @(Orange,Lemmon)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)(Lemmon,Coke)
    @(Orange,Coke)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)
    @(Orange,Pine apple)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)
    @(Orange,W grape)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)
    @(Orange,Appletizer)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)
    @(Orange,R Grape)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)
    @(Orange,Sprite)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)
    @(Orange,Granadilla)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)
    @(Orange,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(Orange,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(Orange,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Orange,Cocoa)(Cocoa,Pawpaw)
    @(Orange,Pawpaw)
    @(Lemmon,Coke)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)(Coke,Pine apple)
    @(Lemmon,Pine apple)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)
    @(Lemmon,W grape)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)
    @(Lemmon,Appletizer)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)
    @(Lemmon,R Grape)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)
    @(Lemmon,Sprite)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)
    @(Lemmon,Granadilla)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)
    @(Lemmon,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(Lemmon,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(Lemmon,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Lemmon,Cocoa)(Cocoa,Pawpaw)
    @(Lemmon,Pawpaw)
    @(Coke,Pine apple)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)(Pine apple,W grape)
    @(Coke,W grape)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)
    @(Coke,Appletizer)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)
    @(Coke,R Grape)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)
    @(Coke,Sprite)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)
    @(Coke,Granadilla)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)
    @(Coke,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(Coke,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(Coke,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Coke,Cocoa)(Cocoa,Pawpaw)
    @(Coke,Pawpaw)
    @(Pine apple,W grape)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)(W grape,Appletizer)
    @(Pine apple,Appletizer)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)
    @(Pine apple,R Grape)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)
    @(Pine apple,Sprite)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)
    @(Pine apple,Granadilla)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)
    @(Pine apple,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(Pine apple,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(Pine apple,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Pine apple,Cocoa)(Cocoa,Pawpaw)
    @(Pine apple,Pawpaw)
    @(W grape,Appletizer)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)(Appletizer,R Grape)
    @(W grape,R Grape)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)
    @(W grape,Sprite)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)
    @(W grape,Granadilla)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)
    @(W grape,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(W grape,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(W grape,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(W grape,Cocoa)(Cocoa,Pawpaw)
    @(W grape,Pawpaw)
    @(Appletizer,R Grape)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)(R Grape,Sprite)
    @(Appletizer,Sprite)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)
    @(Appletizer,Granadilla)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)
    @(Appletizer,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(Appletizer,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(Appletizer,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Appletizer,Cocoa)(Cocoa,Pawpaw)
    @(Appletizer,Pawpaw)
    @(R Grape,Sprite)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)(Sprite,Granadilla)
    @(R Grape,Granadilla)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)
    @(R Grape,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(R Grape,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(R Grape,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(R Grape,Cocoa)(Cocoa,Pawpaw)
    @(R Grape,Pawpaw)
    @(Sprite,Granadilla)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)(Granadilla,Strawbery)
    @(Sprite,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(Sprite,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(Sprite,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Sprite,Cocoa)(Cocoa,Pawpaw)
    @(Sprite,Pawpaw)
    @(Granadilla,Strawbery)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)(Strawbery,Stone)
    @(Granadilla,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(Granadilla,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Granadilla,Cocoa)(Cocoa,Pawpaw)
    @(Granadilla,Pawpaw)
    @(Strawbery,Stone)(Stone,Yam)(Stone,Yam)(Stone,Yam)
    @(Strawbery,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Strawbery,Cocoa)(Cocoa,Pawpaw)
    @(Strawbery,Pawpaw)
    @(Stone,Yam)(Yam,Cocoa)(Yam,Cocoa)
    @(Stone,Cocoa)(Cocoa,Pawpaw)
    @(Stone,Pawpaw)
    @(Yam,Cocoa)(Cocoa,Pawpaw)
    @(Yam,Pawpaw)
    @(Cocoa,Pawpaw)

    Your program description makes no sense. What exactly is it supposed to do?
    Your errors make no sense. What is it doing wrong?
    Your program output makes no sense. Look up pre-order, in-order, and post-order notation for representing trees. Pick one of those that you think would be best. I would go with pre-order. Because what you are doing isn't understandable.
    By the way, I think your concept of a tree is flawed. A node in a tree has 3 things. it has a reference to its parent, it has references to any of its children, and it has some key value that represents the node (if each node were represented by numbers, the value would be an integer or something). In the case of the root, its reference to its parent is null. I don't know what you are doing with your tree, but it is highly confusing.

  • Problems with XMLType and namespace

    Dear subscribers:
    I have been using XMLType successfully with simple XMLs - without namespaces. Now I must handle messages with "xmlns" and it seems XMLType is failing.
    I tested the following XML, extracted from w3c.org examples:
    <?xml version="1.0"?>
    <bk:book xmlns:bk=''urn:loc.gov:books''
    xmlns:isbn=''urn:ISBN:0-395-36341-6''>
    <bk:title>Cheaper by the Dozen</bk:title>
    <isbn:number>1568491379</isbn:number>
    </bk:book>
    The result of “xmlt.getRootElement()” is “book”.
    However, the use of “xmlt.extract( 'book' )” returns an empty object:
    xmlt1 := xmlt.extract( 'book' );
    dbms_output.put_line( 'StringVal: ' || xmlt1.getStringVal() );
    ORA-30625: method dispatch on NULL SELF argument is disallowed
    The following usages also raise errors:
    xmlt1 := xmlt.extract( 'bk:book' );
    ORA-31011: XML parsing failed ORA-19202: Error occurred in XML processing LPX-00601: Invalid token in: 'bk:book' ORA-06512: at "SYS.XMLTYPE", line 111
    xmlt1 := xmlt.extract( 'bk::book' );
    ORA-31011: XML parsing failed ORA-19202: Error occurred in XML processing LPX-00601: Invalid token in: 'bk::book' ORA-06512: at "SYS.XMLTYPE", line 111
    xmlt1 := xmlt.extract( 'book', 'bk' );
    ORA-31013: Invalid XPATH expression ORA-06512: at "SYS.XMLTYPE", line 119
    I am using Oracle version 10.2.0.1.0. Had someone also faced this problem?
    The code I used to test is at the end of this message.
    Thanks in advance
    ====================================
    DECLARE
    xml varchar2(32000);
    xmlt XMLType;
    xmlt1 XMLType;
    root varchar2(3000);
    BEGIN
    --Example from w3c.org
    xml := '<?xml version="1.0"?>
    <bk:book xmlns:bk=''urn:loc.gov:books''
    xmlns:isbn=''urn:ISBN:0-395-36341-6''>
    <bk:title>Cheaper by the Dozen</bk:title>
    <isbn:number>1568491379</isbn:number>
    </bk:book>';
    xmlt := XMLType( xml );
    root := xmlt.getRootElement();
    dbms_output.put_line( 'StringVal: ' || xmlt.getStringVal() ); -- The XML is ok…
    dbms_output.put_line( 'Namespace: ' || xmlt.getNameSpace() ); -- Returns NULL
    dbms_output.put_line( 'Root element: ' || root ); -- Returns ‘book’
    dbms_output.put_line( 'Exists: ' || xmlt.existsNode('book') ); -- Returns ZERO
    xmlt1 := xmlt.extract( 'bk:book' ); Raises error (see above)
    xmlt1 := xmlt.extract( 'bk::book' ); Raises error (see above)
    xmlt1 := xmlt.extract( 'book', 'bk' ); Raises error (see above)
    --xmlt1 := xmlt.extract( 'book' );
    dbms_output.put_line( 'StringVal: ' || xmlt1.getStringVal() ); Raises error
    END;
    /

    If you put your XML into a namespace then you also need to extract from that namespace.... e.g.
    No namespace...
    SQL> select t.xml.extract('myroot')
    2 from (select XMLTYPE('<myroot><mychild>test</mychild></myroot>') as xml from dual) t
    3 ;
    T.XML.EXTRACT('MYROOT')
    <myroot>
    <mychild>test</mychild>
    </myroot>Put XML in namespace and now the extract returns nothing...
    SQL> ed
    Wrote file afiedt.buf
    1 select t.xml.extract('myroot')
    2* from (select XMLTYPE('<myroot xmlns="fred"><mychild>test</mychild></myroot>') as xml from dual) t
    3 /
    T.XML.EXTRACT('MYROOT')
    --------------------------------------------------------------------------------------------------------Extract, specifying the namespace to extract from and now returns the result...
    SQL> ed
    Wrote file afiedt.buf
    1 select t.xml.extract('myroot', 'xmlns="fred"')
    2* from (select XMLTYPE('<myroot xmlns="fred"><mychild>test</mychild></myroot>') as xml from dual) t
    SQL> /
    T.XML.EXTRACT('MYROOT','XMLNS="FRED"')
    <myroot xmlns="fred">
    <mychild>test</mychild>
    </myroot>
    SQL>;)

  • Problem with tree view alignment

    http://tinypic.com/r/34o1wjl/6
    please view the link !!
    i want the tree for the Finished product just below the Raw Material, where as i am not able to achieve it. The raw material gets place in a separate box and finished in another.
    the code for the above is :
    public VBox addVBox()
    VBox vbox = new VBox();
    vbox.setPadding(new Insets(10)); // Set all sides to 10
    vbox.setSpacing(8); // Gap between nodes
    TreeItem<String> inventoryRM = new TreeItem<String> ("Raw Materials");
    inventoryRM.setExpanded(false);
    TreeItem<String> itemRM1 = new TreeItem<String> ("Add Raw Material");
    inventoryRM.getChildren().add(itemRM1);
    TreeItem<String> itemRM2 = new TreeItem<String> ("Edit Raw Material");
    inventoryRM.getChildren().add(itemRM2);
    TreeItem<String> itemRM3 = new TreeItem<String> ("Delete Raw Material");
    inventoryRM.getChildren().add(itemRM3);
    TreeItem<String> inventoryFinished = new TreeItem<String> ("Finished Product");
    inventoryFinished.setExpanded(false);
    TreeItem<String> itemF1 = new TreeItem<String> ("Add");
    inventoryFinished.getChildren().add(itemF1);
    TreeView<String> treeRM = new TreeView<String> (inventoryRM);
    TreeView<String> treeFinished = new TreeView<String> (inventoryFinished);
    vbox.getChildren().addAll(treeRM,treeFinished);
    return vbox;
    }

    If I understand correctly, you're looking for a single tree with two top-level nodes "Raw Materials" and "Finished Product".
    You can achieve this with
    public VBox addVBox()
      VBox vbox = new VBox();
      vbox.setPadding(new Insets(10)); // Set all sides to 10
      vbox.setSpacing(8); // Gap between nodes
      TreeItem<String> inventoryRM = new TreeItem<String> ("Raw Materials");
      inventoryRM.setExpanded(false);
      TreeItem<String> itemRM1 = new TreeItem<String> ("Add Raw Material");
      inventoryRM.getChildren().add(itemRM1);
      TreeItem<String> itemRM2 = new TreeItem<String> ("Edit Raw Material");
      inventoryRM.getChildren().add(itemRM2);
      TreeItem<String> itemRM3 = new TreeItem<String> ("Delete Raw Material");
      inventoryRM.getChildren().add(itemRM3);
      TreeItem<String> inventoryFinished = new TreeItem<String> ("Finished Product");
      inventoryFinished.setExpanded(false);
      TreeItem<String> itemF1 = new TreeItem<String> ("Add");
      inventoryFinished.getChildren().add(itemF1);
      TreeItem<String> rootNode = new TreeItem<String>("");
      rootNode.getChildren().addAll(inventoryRM, inventoryFinished);
      TreeView<String> tree = new TreeView<String> (rootNode);
      tree.setShowRoot(false);
      vbox.getChildren().addAll(tree);
      return vbox;
    }

  • Binary Search Tree

    Hello,
    I'm working on a BinarySearchTree and I am looking for a little bit of advice for my find method or overall optimization comments. For some reason when I set 'found' = null at the beginning of the method I am getting nullpointer exception. But, if I put it in the else statement, it never gets executed. As you can see, find is recursive function. Any help or advice would be greatly appreciated. Thanks in advance!!!!!
    * All items are ordered so that all items in the left subtree are smaller
    * than the item in the root and all items in the right subtree are larger
    * than the item in the root. This is true for all nodes in the tree.
    * No duplicates are allowed.
    * This tree is specific to the doctor's office application and therefore
    * contains Procedure objects - it is expected that Procedure objects are
    * comparable.
    public class BinarySearchTree {
         * The item stored in the root of this BinarySearchTree
        private Procedure value;
         * The parent of this BinarySearchTree
        private BinarySearchTree parent;
         * The left child of this BinarySearchTree
         return found;
         * Print the values of all the nodes of the BinarySearchTree rooted
         * at this node in infix order, one value per line.
        public void inOrder() {
             if ( leftChild != null ) {
                 leftChild.inOrder();
             System.out.println( value.toString() );
             if ( rightChild != null ) {
                 rightChild.inOrder();
    } // BinarySearchTree    */
        private BinarySearchTree leftChild;
         * The right child of this BinarySearchTree
        private BinarySearchTree rightChild;
         * A constructor used for the first node in the tree.
         * There is no parent.
         * @param item The value to be stored at this node of the tree.
        public BinarySearchTree( Procedure item ) {
           value = item;
           leftChild = null;
           rightChild = null; 
         * Accessor function for the value at this node
         * @return the value at this node.
        public Procedure getValue() {
            return value;
         * Accessor function for the parent of this node.
         * @return the parent of this node.
        public BinarySearchTree getParent() {
            return parent;
         * Accessor function for the left child of this node.
         * It allows me to move to the left child.
         * @return the left child of this node.
        public BinarySearchTree getLeftChild() {
            return leftChild;
         * Accessor function for the right child of this node.
         * It allows me to move to the right child.
         * @return the right child of this node.
        public BinarySearchTree getRightChild() {
            return rightChild;
         * Change the left child of this node.
         * @param newLeft the new left child
        private void setLeftChild( BinarySearchTree newLeft ) {
         return found;
         * Print the values of all the nodes of the BinarySearchTree rooted
         * at this node in infix order, one value per line.
        public void inOrder() {
             if ( leftChild != null ) {
                 leftChild.inOrder();
             System.out.println( value.toString() );
             if ( rightChild != null ) {
                 rightChild.inOrder();
    } // BinarySearchTree       leftChild = newLeft;
            leftChild.setParent( this );
         * Change the right child of this node.
         * @param newRight the new right child
        private void setRightChild( BinarySearchTree newRight ) {
            rightChild = newRight;
            rightChild.setParent( this );
         * Change the parent of this node.
         * @param newParent the new parent
         return found;
         * Print the values of all the nodes of the BinarySearchTree rooted
         * at this node in infix order, one value per line.
        public void inOrder() {
             if ( leftChild != null ) {
                 leftChild.inOrder();
             System.out.println( value.toString() );
             if ( rightChild != null ) {
                 rightChild.inOrder();
    } // BinarySearchTree
        private void setParent( BinarySearchTree newParent ) {
            parent = newParent;
         * Add a new item to the tree. If the item is smaller than
         * the value stored at the root node, find a place for it in
         * the left subtree.
         * @param item the item to be added to the tree.
        public void add( Procedure item ){
            BinarySearchTree curNode = this;
            if ( item.compareTo( value ) == 0 ) {
                System.err.println( "Can't have duplicate items in the tree" );
            } else if ( item.compareTo( value ) < 0 ) {
                if ( leftChild != null ) {
                    curNode = leftChild;
                    curNode.add( item );
                } else {
                    curNode.setLeftChild( new BinarySearchTree( item ) );
            } else if ( item.compareTo( value ) > 0 ) {
                if ( rightChild != null ) {
                    curNode = rightChild;
                    curNode.add( item );
                } else {
                    curNode.setRightChild( new BinarySearchTree( item ) );
         * Is the Procedure named in the parameter in the tree? Case is
         * ignored when doing the comparison. If the Procedure is found,
         * return it. If not, print a message and return null.
         * The purpose of the message is for you to KNOW that an item was
         * not found in the tree. Use the format:
         *     'item' not found in the binary search tree
         * where item is the name of the procedure that you are looking for.
         * @param  item The item to look for
        public Procedure find( String item ) {
         BinarySearchTree curNode = this;
         //???????blows up when I set it to null here
         Procedure found = null;
         if ( item.compareToIgnoreCase( value.getName() ) == 0 ) {
             found = value;
             System.out.println("**********************************"
                         + "***************************found it");
         else if ( item.compareToIgnoreCase( value.getName() ) < 0 ) {
                if ( leftChild != null ) {
              System.out.println("LLLLLLLLLLLLLLLLLLLLLLLLLLLLLL");
                    curNode = leftChild;
                    curNode.find( item );
            } else if ( item.compareToIgnoreCase( value.getName() ) > 0 ) {
                if ( rightChild != null ) {
              System.out.println("RRRRRRRRRRRRRRRRRRRRRRRRRRRRR");
                    curNode = rightChild;
                    curNode.find( item );
            //??????NEVER GETS EXECUTED WHEN I UNCOMMENT THIS OUT!!!
         //     else {
         //  found = null;
         //  System.err.println( item
         //          + "7777777777777777777777777777777777777777not found in the binary search tree");
         return found;
         * Print the values of all the nodes of the BinarySearchTree rooted
         * at this node in infix order, one value per line.
        public void inOrder() {
             if ( leftChild != null ) {
                 leftChild.inOrder();
             System.out.println( value.toString() );
             if ( rightChild != null ) {
                 rightChild.inOrder();
    } // BinarySearchTree

    For some reason when I set 'found' = null at the
    beginning of the method I am getting nullpointer
    exception.That must come from outside find() method since nothing in find() uses the value of the "found" variable.
    But, if I put it in the else statement, it never
    gets executed.That's because your if-else-else already considers all the possible cases -- the value that compareToIgnoreCase returns is either equal to, less than, or greater than 0. It can never be anything else.
    You only assign to the local variable "found" if the searched item was found immediately from the 'current node' (= the root); if the item was in the left or right subtree you are happily ignoring it. You needfound = curNode.find( item );in both of the else-cases.
    The item is "not found" when it should be in the left/right child by the comparison test, but the left/right child is empty. So the find() method needs this, and the same for the left childif (compare to > 0) {
        if ( rightChild != null ) {
            // find from child
        } else {
            // not found from tree at all
    }The "not found" code would have to be duplicated, so you should refactor the conditions...Here's a possibility:     if ( item is value ) {
                 // found it in the current node
            else if (item is less than value and leftChild is not null) {
                 // try to find it in the left child
            else if (item is greater than value and rightChild is not null) {
                  // try to find it in the right child
            else {
                  // should be in right/left child but
                  // it's empty --- not found!
            }

  • Binary search tree errors

    MORE A CRY FOR HELP THEN A QUESTION-THANKS!
    I'm having some diffucilites debugging errors produced by my binary search tree class. Spent alot of time trying correct them but just doesn't seem to be working for me :|!. I'm working with two main classes BinaryNode and BinarySearchTree.
    class BinaryNode<AnyType> extends BinarySearchTree
        // Constructor
        BinaryNode(AnyType theElement)
            element = theElement;
            left = right = null;
          // Data; accessible by other package routines
        AnyType             element;  // The data in the node
        BinaryNode<AnyType> left;     // Left child
        BinaryNode<AnyType> right;    // Right child
    public class BinarySearchTree<AnyType extends Comparable<? super AnyType>>
          /** The tree root. */
        protected BinaryNode<AnyType> root;
        private int[] unsorted = new int[] {3,6,7,2,1};
         * Construct the tree.
        public BinarySearchTree()
         root = null;
         * Insert into the tree.
         * @param x the item to insert.
         * @throws DuplicateItemException if x is already present.
        public void insert(AnyType x)
            root = insert(x, root);
         * Remove from the tree..
         * @param x the item to remove.
         * @throws ItemNotFoundException if x is not found.
        public void remove(AnyType x)
            root = remove(x, root);
         * Remove minimum item from the tree.
         * @throws ItemNotFoundException if tree is empty.
        public void removeMin()
            root = removeMin(root);
         * Find the smallest item in the tree.
         * @return smallest item or null if empty.
        public BinaryNode<AnyType> findMin()
         //uses a helpler method that iterates over the left hand of the binary tree
            return(findMin(root));
         * Find the largest item in the tree.
         * @return the largest item or null if empty.
        public BinaryNode<AnyType> findMax()
            return (findMax(root));
         * Find an item in the tree.
         * @param x the item to search for.
         * @return the matching item or null if not found.
        public AnyType find(AnyType x)
            return elementAt(find(x,root));
         * Make the tree logically empty.
        public void makeEmpty()
            root = null;
         * Test if the tree is logically empty.
         * @return true if empty, false otherwise.
        public boolean isEmpty()
            return root == null;
         * Internal method to get element field.
         * @param t the node.
         * @return the element field or null if t is null.
        public AnyType elementAt(BinaryNode<AnyType> t)
            return t == null ? null : t.element;
         * Internal method to insert into a subtree.
         * @param x the item to insert.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws DuplicateItemException if x is already present.
        protected BinaryNode<AnyType> insert(AnyType x, BinaryNode<AnyType> t)
            if(t == null) {
                t = new BinaryNode<AnyType>(x);
            else if(x.compareTo(t.element) < 0) {
                t.left = insert(x, t.left);
            else if(x.compareTo(t.element) > 0 ) {
                t.right = insert(x, t.right);
            else {
                throw new DuplicateItemException(x.toString());  // Duplicate
            return t;
         * Internal method to remove from a subtree.
         * @param x the item to remove.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws ItemNotFoundException if x is not found.
        protected BinaryNode<AnyType> remove(AnyType x, BinaryNode<AnyType> t)
            if(t == null) {
                throw new ItemNotFoundException(x.toString());
            if(x.compareTo(t.element) < 0) {
                t.left = remove(x,t.left);
            else if(x.compareTo(t.element) > 0) {
                t.right = remove(x, t.right);
            else if(t.left != null && t.right != null) // Two children
                t.element = findMin(t.right).element;
                t.right = removeMin(t.right);
            else {
                t = (t.left != null) ? t.left : t.right;
            return t;
         * Internal method to remove minimum item from a subtree.
         * @param t the node that roots the tree.
         * @return the new root.
         * @throws ItemNotFoundException if t is empty.
        protected BinaryNode<AnyType> removeMin(BinaryNode<AnyType> t)
            if(t == null) {
                throw new ItemNotFoundException();
            else if(t.left != null) {
                t.left = removeMin(t.left);
                return t;
            else {
                return t.right;
        * Given a non-empty binary search tree,
        * return the minimum data value found in that tree.
        * Note that the entire tree does not need to be searched.
        * @param t the node that roots the tree.
        * @return node containing the smallest item.
        protected BinaryNode<AnyType> findMin(BinaryNode<AnyType> t)
            if(t != null) {
                while(t.left != null) {
                    t = t.left;
            return t; //the smallest value
         * Internal method to find the largest item in a subtree.
         * @param t the node that roots the tree.
         * @return node containing the largest item.
        protected BinaryNode<AnyType> findMax(BinaryNode<AnyType> t)
            if(t != null) {
                while(t.right != null) {
                    t = t.right;
            return t; //the largest value
         * Internal method to find an item in a subtree.
         * @param x is item to search for.
         * @param t the node that roots the tree.
         * @return node containing the matched item.
        private BinaryNode<AnyType> find(AnyType x, BinaryNode<AnyType> t)
            while(t != null) {
                if(x.compareTo(t.element) < 0) {
                    t = t.left;
                else if(x.compareTo(t.element) > 0) {
                    t = t.right;
                else {
                    return t;    // Match
            return null;         // Not found
        public void betweenTraverse() {
         betweenTraverse(root);
        * Given two integers,
        * print all the values in the tree which are between these two numbers
        * in ascending order.
        * @param t is BinaryTree to search through
        * @param a is min integer to start print from
        * @param b is max integer to keep integer print between
        private void betweenTraverse(BinaryNode<AnyType> t)
         //enter samllest vaule
         int a = System.in.read();
         //enter largetest vaule
         int b = System.in.read();
         if (t != null) {
             inorderTraverse(t.left);
             if(t.elementAt(t) >a && t.elementAt(t) < b) { //LINE 274 with error
              System.out.println(t.elementAt(t));
             inorderTraverse(t.right);
        * Given an array of unsorted integers 
        * adds add the these elements of unsorted as nodes
        * to an initially empty binary search tree
        * @param x is array which it element to be added to a binary tree
        public BinarySearchTree<Integer> numberstoTree(int[] x)
         BinarySearchTree<Integer> treeOne = new BinarySearchTree<Integer>();
         Arrays.sort(x);
         for (int i = 0 ; i < x.length ; i++) {
                int j = x;
         treeOne.insert(j);     
         treeOne.inorderTraverse();
         return treeOne;
    public void inorderTraverse() {
         inorderTraverse(root);
    private void inorderTraverse(BinaryNode<AnyType> t) {
         if (t != null) {
         inorderTraverse(t.left);
         System.out.println(t.elementAt(t));
         inorderTraverse(t.right);
    // Test program
    public static void main(String[] args)
    BinarySearchTree<Integer> t = new BinarySearchTree<Integer>();
    final int NUMS = 4000;
    final int GAP = 37;
    System.out.println("Checking... (no more output means success)");
    for( int i = GAP; i != 0; i = ( i + GAP ) % NUMS ) {
    t.insert(i);
    for(int i = 1; i < NUMS; i += 2) {
    t.remove(i);
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) { //LINE 332 with error
    System.out.println("FindMin or FindMax error!");
    for(int i = 2; i < NUMS; i += 2) {
         if( t.find(i) != i) {
    System.out.println("Find error1!");
    for(int i = 1; i < NUMS; i += 2) {
    if(t.find(i) != null) {
    System.out.println("Find error2!");
    }I getting these errors:BinarySearchTree.java:274: operator > cannot be applied to java.lang.Comparable,int
         if(t.elementAt(t) >a && t.elementAt(t) < b) {
    ^
    BinarySearchTree.java:274: operator < cannot be applied to java.lang.Comparable,int
         if(t.elementAt(t) >a && t.elementAt(t) < b) {
    ^
    BinarySearchTree.java:332: elementAt(BinaryNode) in BinarySearchTree cannot be applied to (BinarySearchTree<java.lang.Integer>)
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) {
    ^
    BinarySearchTree.java:332: cannot find symbol
    symbol : method elementAt(BinarySearchTree<java.lang.Integer>)
    location: class java.lang.Integer
    if(t.findMin().elementAt(t) != 2 || t.findMax().elementAt(t) != NUMS - 2) {
    ^ I've tried to change the method return types, to integer, AnyType but still producing more or same amount of errors, any help debugging this would be so helpful!.
    Thanks                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

    So i've tried to re implement the static statements. i.e
    if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {
                System.out.println("FindMin or FindMax error!");
         }but now receiving this error :
    BinarySearchTree.java: operator > cannot be applied to java.lang.Comparable,java.lang.Integer
             if(t.elementAt(t) > A && t.elementAt(t) < B) { //LINE 274 WITH ERROR
                                  ^
    BinarySearchTree.java: operator < cannot be applied to java.lang.Comparable,java.lang.Integer
             if(t.elementAt(t) > A && t.elementAt(t) < B) { //LINE 274 WITH ERROR
                                                        ^
    BinarySearchTree.java: cannot find symbol
    symbol  : method compareTo(java.lang.Integer)
    location: class BinaryNode<java.lang.Integer>
            if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {
                        ^
    BinarySearchTree.java: cannot find symbol
    symbol  : method compareTo(java.lang.Integer)
    location: class BinaryNode<java.lang.Integer>
            if(t.findMin().compareTo(t.elementAt(t.root)) != 2 || t.findMax().compareTo(t.elementAt(t.root)) != NUMS - 2) {The method compareTo takes an object as defined in the comparable interface which my BinarySearchTree extends. Binary Node is a child of BinarySearchTree. I've been messing around with where i initiate the compareTo method but not had any success, any idea/push in the right direction would be appreciated.
    Thanks

  • Question about binary search tree

    i was asked to do a programe that generating 1000 random integer numbers between 1 - 50, storing each unique number and it's corresponding occurrence into a binary search tree and output them in asending order. Therefore, before, adding the new number into the tree, i have to compare it with others that have been stored in the tree. and i did it in the following code segment.
    public void compare(int number)
       NumberObject newNumObj = new NumberObject(number);
       boolean b = true;
       if(isEmpty())
        root = new BinarySearchTreeNode(newNumObj, null, null); //assuming BSTNode class in somewhere else
       else
        b = find(root, newNumObj);
        if(b == false)
         add(newNumObj);
    private boolean find(BinarySearchTreeNode node, NumberObject newNumObj)
        int relation = ((Comparable)newNumObj).compareTo(node.getObject());
        //******************** QUESTION IS HERE ******************
        if(relation == 0) 
         (node.getObject()).setCount(); //increase that number object's account
          newNumObj = null;  //recycle newNumObj if it's the same as one stored in the tree
          return true;
       //****************** ENDS QUESTION ********************************
        else if(relation > 0)
          find(node.right, newNumObj);
        else if(relation < 0)
          find(node.left, newNumObj);
       return false;
    my question is can i say the new number is the same as the one that already stored in the tree according to the above code? i am not sure cauz there are two attributes: the number and it's frequency stored in one numberObject. and the compareTo method just dealing with the numbers, but nothing particular associated with it's account. so, could anyone help me work out this puzzle? help would be greatly appreciated!

    Not sure whether this is what you want.. But may be it will help....
    import java.util.*; 
    public class Rand{
         public static void main(String arg[]){
              new Rand();      
         Rand(){
              Random random=new Random();
              int ranNo;
              TreeMap map=new TreeMap();
              Integer in;
              for(int i=0;i<1000;i++){
                   ranNo= random.nextInt() ;      
                   ranNo=Math.abs(ranNo);
                   ranNo%=50;
                   in=new Integer(ranNo);
                   if(!(map.containsKey(in)))
                        map.put(in,i+""); 
              Iterator iter=map.keySet().iterator();
              Integer key;
              while(iter.hasNext()){
                   System.out.print( (key=(Integer)iter.next()) + "  ");
                   System.out.println(map.get(key).toString());
    }appu

  • Validating namespace in XPATH

    Hi,
    How do I resolve the namespaces in the XPATH. I'm using Xalan 2.4 package and it's API. I made a simple test program where I pass the Xpath and I get back the node. The problem i'm facing is that if the xml document in question has some namespace declared. In the Xpath expression if I include the name space then it does not return the proper result. Where as when I give the Xpath without the namespace prefix it returns the node. I'm using the evaluate method of the XPathEvaluatorImpl class ( in package org.apache.xpath.domapi). This method takes XPathNSResolver (the namespace resolver) as one of the parameters. I passed that too still the problem persisted. If any one could help me out here it would be great. if you need further details I can post the code.

    To answer my own question..
    The mistake I was commiting was at a very upper level.
    While creating the DOM..the Factory instance I was using was of the type which does not resolve the namespaces properly. That is why even though my XPATH objects had the resolver set properly still I was not able to get to the proper node.
    Sorry If I wasted any one of you's time :)

  • Breadth First Traversal of a Tree...

    Hi,
    I want to make a program to print every node of a tree in a Breadth First Search (BFS)/Traversal. Since, BFS searches a tree in levels (i.e. 1st the root, then it's Children, then Grand Children etc from left to right), this is where I'm stuck. Here is my TreeNode class:
    class TreeNode {
      Object element;
      TreeNode left;
      TreeNode right;
      public TreeNode(Object o) {
        element = o;
    }Each node has a reference to its Children nodes etc. Here is how my tree looks like. Mine is similar to this: http://www.codeproject.com/KB/vb/SimpleBTree.aspx
    All the lectures I have read in the net are talking about Queue, but my problem is reading the tree in BFS Traversal order. It's almost 4 days I'm trying to solve this probelm, but can't come up with something. Any help is greatly appreciated.
    Here is my Binary Tree class:
    public class BinaryTree {
         private TreeNode root;
         private int size = 0;
         /** Create a default binary tree */
         public BinaryTree() {
         /** Create a binary tree from an array of objects */
        public BinaryTree(Object[] objects) {
          for (int i = 0; i < objects.length; i++)
            insert(objects);
    /** Insert element o into the binary tree
    * Return true if the element is inserted successfully */
    public boolean insert(Object o) {
    if (root == null)
    root = new TreeNode(o); // Create a new root
    else {
    // Locate the parent node
    TreeNode parent = null;
    TreeNode current = root;
    while (current != null)
    if (((Comparable)o).compareTo(current.element) < 0) {
    parent = current;
    current = current.left;
    else if (((Comparable)o).compareTo(current.element) > 0) {
    parent = current;
    current = current.right;
    else
    return false; // Duplicate node not inserted
    // Create the new node and attach it to the parent node
    if (((Comparable)o).compareTo(parent.element) < 0)
    parent.left = new TreeNode(o);
    else
    parent.right = new TreeNode(o);
    size++;
    return true; // Element inserted
    /** Inorder traversal */
    public void inorder() {
    inorder(root);
    /** Inorder traversal from a subtree */
    private void inorder(TreeNode root) {
    if (root == null) return;
    inorder(root.left);
    System.out.print(root.element + " ");
    inorder(root.right);
    /** Postorder traversal */
    public void postorder() {
    postorder(root);
    /** Postorder traversal from a subtree */
    private void postorder(TreeNode root) {
    if (root == null) return;
    postorder(root.left);
    postorder(root.right);
    System.out.print(root.element + " ");
    /** Preorder traversal */
    public void preorder() {
    preorder(root);
    /** Preorder traversal from a subtree */
    private void preorder(TreeNode root) {
    if (root == null) return;
    System.out.print(root.element + " ");
    preorder(root.left);
    preorder(root.right);
    /** Inner class tree node */
    private static class TreeNode {
    Object element;
    TreeNode left;
    TreeNode right;
    public TreeNode(Object o) {
    element = o;
    /** Get the number of nodes in the tree */
    public int getSize() {
    return size;
    /** Search element o in this binary tree */
    public boolean search(Object o){
    TreeNode temp = root;
    boolean found = false;
    if(temp == null)
    found = false;
    else if(((Comparable)(temp.element)).compareTo(o) == 0 && temp != null)
    found = true;
    else if(((Comparable)temp.element).compareTo(o) > 0){
    root = temp.left;
    found = search(o);
    else{
    root = temp.right;
    found = search(o);
    return found;
    /** Display the nodes in breadth-first traversal */
    public void breadthFirstTraversal(){
    TreeNode temp = root;
    // TreeNode leftChild = temp.left;
    // TreeNode rightChild = temp.right;
    MyQueue s = new MyQueue();
    s.enqueue(root);
    // while (s.getSize() == 0){
    System.out.println(s);
    // private void breadthFirstTraversal(TreeNode node){

    ChangBroot wrote:
    All the lectures I have read in the net are talking about Queue, but my problem is reading the tree in BFS Traversal order. It's almost 4 days I'm trying to solve this probelm, but can't come up with something. Any help is greatly appreciated. One simple strategy is to make an ordinary recursive traversal of the tree. Along in the traversal you keep an array of linked lists. When you visit a node you just add it to the list at the entry in the array corresponding to the depth of this node.
    After the traversal you have an array with linked lists. Each list holds the nodes found at a certain tree depth. So each list holds all nodes corresponding to a specific tree "breadth", namely all nodes found at the same tree depth.

  • Xpath and namespace tag problem...

    hello,
    I have added targetNamespaces to a schema from which i am producing objects via JAXB. it has resulted in a problem!
    Orignal xml document entry produced by JAXB:
    <job>
    <operationName>Operation Test</operationName>
    </job>
    New xml document entry produced by JAXB :
    <job>
    <operationName xmlns="http://www.me.co.uk/me/bus"> Operation Test</operationName>
    </job>
    Xpath query:
    "/job/operationName"
    returned a value ("Operation Test"), now with the namespace modifications it returns "" Any ideas?
    I tried
    /job/operationName/[@*] but still got nothing back
    cheers
    m

    It is possible to use xpath when working with default namespaces. I do not use jaxB, but with jaxP en the methods described in: http://java.sun.com/developer/technicalArticles/xml/validationxpath/
    it all works.
    Example:
    java-code
    import org.w3c.dom.*;
    import javax.xml.xpath.*;
    import org.xml.sax.SAXException;
    try {
        DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
        Document document = builder.parse(new File("users.xml"));
        String expression = "/users/user[@id='0']";
        XPath xpath = XPathFactory.newInstance().newXPath();
        Node userNode = (Node) xpath.evaluate(expression, doc, XPathConstants.NODE);
    } catch (SAXException se) {
        se.printStackTrace();
    } catch (XPathExpressionException xe){
        xe.printStackTrace();
    user.xml
    <users
              xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
              xmlns="http://www.sphemy.com/xmlrss/user"
              xsi:schemaLocation="http://www.sphemy.com/xmlrss/user user.xsd">
         <user id="0">
              <loginName>guest</loginName>
              <password>guest</password>
         </user>
    </users>
    user.xsd
    <xs:schema
              xmlns:xs="http://www.w3.org/2001/XMLSchema"
              xmlns="http://www.sphemy.com/xmlrss/user"
              targetNamespace="http://www.sphemy.com/xmlrss/user"
              elementFormDefault="qualified">
         <xs:element name="users">
              <xs:complexType>
                   <xs:sequence>
                        <xs:element name="user" type="UserType" maxOccurs="unbounded"/>
                   </xs:sequence>
              </xs:complexType>
         </xs:element>
         <xs:complexType name="UserType">
              <xs:sequence>
                   <xs:element name="loginName" type="xs:string"/>
                   <xs:element name="password" type="xs:string"/>
              </xs:sequence>
         </xs:complexType>
    </xs:schema>Edited by: sphemy on Jan 2, 2009 4:50 AM

  • XPath function namespace-uri in Mediator raises ORAMED-01004

    Hi,
    In a mediator component (SOA Suite 11g) I try to use some XPath functions.
    "name" and "local-name" do just fine, but when I try to use "namespace-uri" I always get an ORAMED-01004 error.
    Like this:
    oracle.tip.mediator.infra.exception.MediatorException: ORAMED-01004:[Multiple source nodes]Source expression "namespace-uri($in.berichtPart/child::*)" resulted in multiple node for source message which is not supportedPossible Fix:Please check expression for correctness. Modify source expression based on the requirement otherwise contact Oracle for support
    I seems like a bug to me as namespace-uri should return a string, just like name and local-name...
    Xpath spec: Function: string namespace-uri(node-set?)
    Can anyone confirm? Am I missing something???
    Groeten,
    HJH

    Any solution to this?

  • Tree tags selected lines out of order

    Why is it that tree controls return the tags of the items selected in the order they are selected, whereas the listbox returns the row number of the items selected in numeric order? Is there any way to have a tree control return the selected items in the order they appear on screen?
    Michael

    I've attached an example illustrating how listboxes return selected items in order and trees do not. If you click on one of the bottom items, hold control, then click on one of the top items, the listbox will return the row numbers in numeric order whereas the tree returns the tags in the order you clicked them. It would be nice if the tree returned the tags in the order on the screen.
    The actual code I am using the tree in is for a plot legend that allows users to select which graphs to make visible. I've already made a workaround that works fine, I was just trying to use a for loop that looked at each item in the listbox or tree and made a plot visible or invisible according to the items selected. However, this required selected items to be in order. I know this probably isn't a very common use of a tree, since I only deal with parents, but some features involving cell coloring when cells are deleted work very well for my application.
    If the ordering is just how it is for trees, I guess I'll have to accept it....
    Michael

  • MorseCode Binary Tree

    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 BinaryTree

    As 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.

Maybe you are looking for

  • How to print the JFrame In The Center Of The Page?

    hi there in the following code iam trying to print a JFrame but the frame appear in the printed page at the top left and i want it to appear in the top center of the page how to do that? import java.awt.*; import java.awt.event.*; import javax.swing.

  • Sorting for  storage type in LM12

    LM12 - change sort display so that alpha storage types with bin info displayed before numeric storage type and bin info. The standard LM12 shows sort order for storage type as  numeric storage types first then alpha storage types. But User is request

  • Thumbnail view not there anymore how do I get it back?

    A few days ago I had the ability to choose how I view my photo files in all my photoshop applications. I have been able to do this for years. This week I turned on my computer, opened my adobe CS6 and all I could do was chose size of my PSD icons! Wh

  • Can I create a mirror image of a 3D object without flattening it?

    I'd like an exact copy of a 3D object I made to be looking back across my image at the other one. I feel retaining the 3D functionality of the second object enhances the authenticity of the image and keeps more options open if I decide I need to repo

  • Recommend datafile size on Linux

    Hi Can anyone suggest in general what is the max recommended datafile size for Oracle database (8i,9i, 10g) on linux platforms. datafiles are placed located on local server and i dont prefer keeping the autoextend on for Prod databases. I heard that