N-ary Trees non-recursive traversal algorithms

Hi,
Non-recursive traversals are needed when you are unsure how big the tree's will be. So far all the algorithms I have seen either use their own internal stack
or threading to climb back up the tree.
Here's my attempt that seems to work but I would value so critical evaluation
* An extension of the CommonAST that records the line and column
* number.  The idea was taken from <a target="_top"
* href="http://www.jguru.com/jguru/faq/view.jsp?EID=62654">Java Guru
* FAQ: How can I include line numbers in automatically generated
* ASTs?</a>.
* @author Oliver Burn
* @author lkuehne
* @version 1.0
* @see <a target="_top" href="http://www.antlr.org/">ANTLR Website</a>
public class DetailAST
    public AST getFirstChild()
    public AST getNextSibling()
    public int getChildCount()
    public DetailAST getParent()
    public int getChildCount(int aType)
    public String getText()
}This was cut back just to give you enough info
     public static AST getLeftMostChild(DetailAST ast) {
          DetailAST tempAst = ast.getFirstChild();
          while (tempAst.getFirstChild() != null) {
               tempAst = tempAst.getFirstChild();
          return tempAst;
     public static void traverseASTInOrder(DetailAST root) {
          DetailAST current = getLeftMostChild(ast);
          processNode(current);
          while (current != root) {
               if (current == current.getParent().getFirstChild()) {
                    processNode(current.getParent());
               if (current.getNextSibling() != null) {
                    DetailAST sibling = current.getNextSibling();
                    if (sibling.getChildCount() != 0) {
                         current = (DetailAST) getLeftMostChild(sibling);
                         processNode(current);
                    } else {
                         current = sibling;
                         processNode(current);
               } else {
                    current = current.getParent();
        // do stuff at inorder traversal
     public static void processNode(AST current) {
          System.out.println(current.getText());
     }for pre-order and post-order John Cowan put forward this algorithm
http://lists.xml.org/archives/xml-dev/199811/msg00050.html
traverse(Node node) {
    Node currentNode = node;
    while (currentNode != null) {
      visit(currentNode); //pre order
      // Move down to first child
      Node nextNode = currentNode.getFirstChild();
      if (nextNode != null) {
        currentNode = nextNode;
        continue;
      // No child nodes, so walk tree
      while (currentNode != null) {
        revisit(currentNode)     // post order
        // Move to sibling if possible.
        nextNode = currentNode.getNextSibling();
        if (nextNode != null) {
          currentNode = nextNode;
          break;
       // Move up
       if (currentNode = node)
      currentNode = null;
       else
      currentNode = currentNode.getParentNode();
  }Any comments, criticisms or suggestions ?
regards
David Scurrah

Stack is recursion? As far as I know recursion is when
function (method) calls itself. Just using some
Collection, which java.util.Stack implements is not
recursion.
Regards
PawelStacks are used to implement recursive algorithms. What happens in most languages when you make a function call? Each function has an "activation record" where it stores its local variables and parameters. This activation record is usually allocated on a stack. Thus for any recursive algorithm, there is a non-recursive algorithm that uses a stack.
In the OP's case you don't need a stack because of the peculiarities of tree traversal when you have a pointer to the parent node. (Namely, no cycles and you can get back to where you've been) So the algorithms he gave should work fine.
My only "criticism" would be that it may be more useful to implement these algorithms with the iterator pattern. So you would have a tree with some functions like:
public class Tree{
    public TreeIterator inOrderIteraror();
    public TreeIterator preOrderIterator();
}Where the TreeIterator would look like a java.util.Iterator, except maybe you want some additional utility methods in there or something.
Other than that, non-recursive algorithms are defnitely the way to go.

Similar Messages

  • Binary tree using inorder traversal algorithm

    I need to draw a Binary tree using Inorder traversal algorithm.. in java applets using rectangles and ellipse objects.. can anyone help me about this ? I will be really thankful to yu

    I think this is my psychic Sunday, so here's my attempt at answering
    this vaguely stated question. First have a look at this fine piece of
    ASCII art:--------------------------------------------   ^         ^
    | A                    T                     |   |         |
    |                                            |   |        root
    ---------L-----------------------R---------+   |         v
    | B                    |  C                  |   |
    |                      |                     |   |
    |                      |                     | height
    |                      |                     |   |
    |                      |                     |   |
    |                      |                     |   |
    |                      |                     |   |
    |                      |                     |   |
    |                      |                     |   |
    |                      |                     |   |
    -------------------------------------------+   v
    <--------------------width------------------->Suppose you have a rectangle 'width' wide and 'height' high. The root
    of the tree can be drawn at position T and (if present), two lines can be
    drawn to the positions L and R respectively. Now recursively call your
    same method using the computed rectangle A and B for the left and
    right subtrees L and R respectively.
    kind regards,
    Jos

  • Non recursive preorder traversal of binary tree

    hi,
    I am trying to implement a non-recursive traversal of binary tree. I already know the recursive one.
    I am trying to do it by using a Stack.
    I begin by Pushing the root of an element on to a stack, and then run a while loop in which i pop an element of the stack and get its children from right to left. and push it in the same order on to the stack. So during the next iteration of my while loop the top most element gets popped and its children and pushed on to the stack in the above manner.
    but when i pop an element from a stack its popped as an object so i dont know how to access its children.
    help me i am really stuck.

    Hi, I suppose you have something like this :
    class Stack {
      public void push( Object object ) throws ... { ... }
      public Object pop() throws ... { ... }
    class Element {
      Element elem;
      stack.push(elem);
      /* because pop() method return an object of type Object
      ** if you are sure that your stack only contains Element object
      ** then you need to cast (change the type of) what the pop() method
      ** returns in this way :
      elem = (Element)stack.pop();
      ...further reading on casting will be a good idea anyway.

  • How to find the level of an n-ary tree

    I have a n-ary tree. I traverse this tree using Breadth First and using queues to store the nodes that I encounter.
    Can anyone tell me how to find the current level I am in this n-ary tree

    How do I do that...My mind is drawing a blank totally
    This code does a breadth first traversal
    private void processTree(Node node) {
    LinkedList queue = new LinkedList();
    queue.addLast(node);
    while (queue.size() > 0) {
         Node node1 =(Node)queue.removeFirst();
         if (node1 != null) {
              processNode(node1);//Do some processing on this node
              NodeList nodeList = node1.getChildNodes();
              for (int i = 0; i < nodeList.getLength(); i++) {
                        queue.addLast(nodeList.item(i));
    Using this how can I determine the level. Since Im visiting each node of a particular level how do I know that a level is over and Im now visitng the next level?

  • How to Recursively traverse a Dom Tree

    Hi there, I'm new to java and xml and would like to see some sample code on recursively traversing a DOM tree in java, printing out all Element, Text, etc to the console window.
    Please help

    Use this: DomRead.java at your own risk. caveat: this gets screwed up if the attributes are multi-valued. You can use XPath to get around that. I am struggling with the proper XPath expressions.
    import org.xml.sax.*;
    import org.w3c.dom.*;
    import java.util.*;
    * version 1.0
    public class DomRead implements ErrorHandler
         private static final String CRLF = System.getProperty("line.separator");
         private static String key = "";
         private static String value = "";
         private Hashtable elements = new Hashtable();
         * This constructor has to be used to pass in the DOM document which needs to
         * be read so that this class can generate the hashtable with the attributes as
         * keys and their corresponding values.
         public DomRead(Document rootDoc)
              process(rootDoc);
         private void processChild(NodeList root)
              for(int i=0;i<root.getLength(); i++)
                   process(root.item(i));
         private void printAttrib(Node root)
              NamedNodeMap attrib = root.getAttributes();
              int len = attrib.getLength();
              if(len == 0) return;
              for(int i=0; i < len ; i++)
                   Attr attribute = (Attr) attrib.item(i);
                   key = attribute.getNodeValue();
         private void process(Node root)
              switch( root.getNodeType())
                   case Node.DOCUMENT_NODE :
                        Document doc = (Document) root;
                        processChild(doc.getChildNodes());
                        break;
                   case Node.ELEMENT_NODE :
                        root.setNodeValue(root.getNodeValue() );
                        printAttrib(root);
                        processChild(root.getChildNodes());
                        break;
                   case Node.TEXT_NODE :                    
                        Text text = (Text) root;
                        value = text.getNodeValue().trim();                    
                        //Log("Value: "+value+CRLF);
                        if(!value.equalsIgnoreCase(""))
                             elements.put(key, value);
                        break;
         * Use this method, if you intend to print out the contents of the generated
         * hashtable.
         public void printElements()
              for (Enumeration enum = elements.keys(); enum.hasMoreElements() ;)
                   String tKey = (String)enum.nextElement();
                   Log(tKey+"::::"+(String)elements.get(tKey));
         * This method returns the Hashtable with the attributes that have non-empty
         * values.
         public Hashtable getElements()
              return elements;
         public void error(SAXParseException e)
              e.printStackTrace();
         public void warning(SAXParseException e)
              e.toString();
         public void fatalError(SAXParseException e)
              e.printStackTrace();
         private static void Log(String log)
              System.out.print(log+CRLF);
    }

  • Non-recursive postorder traversal (bst)

    Hello!
    I'm having difficulty writing a non-recursive postorder traversal for a binary search tree. Not getting an error via compiler but I know that the answer is incorrect. Please provide some insight on what I'm doing wrong!
    Here's an example of what I mean by incorrect..
    correct postorder answer (done recursively) --> 0 4 2 6 10 12 14 8 18 16
    what I'm getting using the function below --> 8 6 2 0 4 14 12 10 18 18
    And here's what I have:
    public void nonRecursivePostorder(BinarySearchTreeNode<T> root, StringBuffer result)
    LinkedStack<BinarySearchTreeNode<T>> stack = new LinkedStack<BinarySearchTreeNode<T>>();
    BinarySearchTreeNode<T> currentNode = root;
    boolean done;
    done = (currentNode == null);
    while (!done)
    if (currentNode.getLeft() != null)
    if (currentNode.getRight() != null)
    stack.push(currentNode.getRight());
    currentNode = currentNode.getLeft();
    else if (currentNode.getRight() != null)
    currentNode = currentNode.getRight();
    else if (stack.empty())
    done = true;
    else
    currentNode = stack.top();
    stack.pop();
    System.out.print(currentNode.getData() + " ");
    }

    When you post code, wrap it in code tags.
    Anyway, ultimately the solution is to put in debugging tags to see where things are going wrong.
    You don't really need that done variable. Just check the stack.
    Though actually IIRC, you'd actually need a queue.

  • Finding a non-recursive algorithm

    I had a project a year ago that was supposed to teach the class recursion. Already being familiar with the Java language, the project was simple.
    The project was, you ahve a "cleaning robot" which cleans an entire room and then returns to the spot it originally was. The room was inputed as a txt file. Everytime you moved to a spot it was automatically cleaned
    The Robot was given to you. The robot class hasthe following methods:
    void move(Direction)   - moves in the direction you gave it.
    boolean canMove(Direction)    -  returns true if the robot can move there without running into a wall
    boolean hasBeen(Direction) - returns true if the robot has cleaned the spot that is in that directionThe Direction class was given to you. It is an enumerated type with the Directions FORWARD, BACWARD, LEFT, RIGHT.
    now the Recursive algorithm is simple:
    private void clean(Direction c, Direction r)
                 move(c); //clean spot in direction
                 for(Direction d : Direction.values()) //go every direction
                      if(canMove(d) && !haveBeen(d)) clean(d,reverse(d));
                 move(r); //go back way we came
    private Direction reverse(Direction d)
                   switch(d)
                      case FORWARD:  d = Direction.BACKWARD; break;
                      case RIGHT:    d = Direction.LEFT;     break;
                      case BACKWARD: d = Direction.FORWARD;  break;
                      case LEFT:     d = Direction.RIGHT;    break;
                 return d;     
    public void start()
             clean(Direction.FORWARD, Direction.BACKWARD);
        }But I am curious how someone would go about implementing a NON recursive algorithm. I understand it would probably be around 2000 lines to implement it. I am not asking anyone to implement it, nor do I plan on it (well..I may one day if I am bored) I am only asking for mere curiosity how someone would go about implementing this non-recursively.
    I have thought about it and thought about it, and the only thing I come up with is recursion. What are your thoughts?

    then I think it'll work.Almost. Your algorithm is flawed in this section:
    move(c);
          // After everything else, come back.
           backtrace.push(reverse(c));What happens when c is the reverse direction? You add to the stack the reverse of the reverse. This means you will continually go back and forth in an infinite loop. I took what you started with and worked it into a working solution:
    private void cleanAll() {
              //imitate the call stack
              Stack<Stack<Direction>> call = new Stack<Stack<Direction>>();
              //holds all the reverse directions     
             Stack<Direction> backtrack = new Stack<Direction>();
             //starting stack
             Stack<Direction> start = new Stack<Direction>();
             //load the starting stack
             for (Direction d : Direction.values())
                  if(canMove(d) && !haveBeen(d))
                       start.push(d);
             call.push(start);
             while (!call.isEmpty()) {
                  Stack<Direction> s = call.pop();
                  while(!s.isEmpty()){
                       Direction c = s.pop();
                      move(c); //clean in this direction
                      backtrack.push(reverse(c)); //record the reverse
                      Stack<Direction> temp = new Stack<Direction>();
                      call.push(s); //stop the current path
                      //load the new stack
                      for (Direction d : Direction.values())
                         if (canMove(d) && !haveBeen(d))
                              temp.push(d);
                     if(!temp.isEmpty())   
                          s = temp; //make temp the current stack
             if(!backtrack.isEmpty())
                  move(backtrack.pop());// After everything else, come back.
        }The problem with your solution is that you use 1 stack for the entire process. In this case, it does not differentiate between moves, so it doesn't KNOW what is a reverse. You need to seperate the reverse directions and treat the different in the special case. In order to do that, you need to know WHEN to reverse. Well you reverse when you have completed a cleaning "path".
    My algorithm implements that "path" as another stack. And adds it to a stack of stacks. What this does is it allows me to know when to reverse. I pop off a stack from the call stack, and then after I am done with that stack I have to reverse, as shown in the code I posted.
    Thank you so much for enhancing my knowledge of Stacks. You have helped emensely. I will be sure to tell my professor that i implemented a iterative solution in about 50 lines of code (extremely lower than the 2000 he hypothosized)

  • Internal error in R-tree processing: [Recursive fetch error]

    Hello,
    I seem to be getting an error when using any type of SDO function (SDO_RELATE, SDO_FILTER, SDO_ NN, ... ) on my spatially indexed data. The error I'm getting is this:
    ERROR at line 1:
    ORA-29903: error in executing ODCIIndexFetch() routine
    ORA-13236: internal error in R-tree processing: []
    ORA-13236: internal error in R-tree processing: [Recursive fetch error]
    The interesting part of this is that I only get this error if I insert more than 31 entries into the table. All the relevant code is posted below, what I do is create the table, then create the metadata from the sqlplus interface. After that I run a java program that does Clear() then Insert() then Create_Indices(). All these run just fine (at least run without telling me about any errors). But as soon as that is all done and I do an SDO query on the data, for example:
    SELECT location stop_range_poly_area
    FROM stops
    WHERE SDO_FILTER
    location,
    SDO_GEOMETRY
    2003, null, null,
    SDO_ELEM_INFO_ARRAY(1,1003,1),
    SDO_ORDINATE_ARRAY(300,300, 600,300, 600,600, 300,600, 300,300)
    ) = 'TRUE';
    I get the above mentioned error. But if I change my data so that it doesn't have more than 31 entries (doesn't matter which 31 entries, just so long as it doesn't exceed that number) that query (and all of my other SDO test queries on the stops table) seems to work just fine.
    Thanks for looking at this,
    Brad
    ---- SQLPLUS Code -----------------------------------------------------------------------------------------------------------
    CREATE TABLE stops
    stop_id VARCHAR2(4) PRIMARY KEY,
    address VARCHAR2(256),
    location sdo_geometry
    INSERT INTO user_sdo_geom_metadata VALUES
    'stops',
    'location',
    MDSYS.SDO_DIM_ARRAY
    MDSYS.SDO_DIM_ELEMENT('X', 0, 600, 0.005),
    MDSYS.SDO_DIM_ELEMENT('Y', 0, 800, 0.005)
    null
    ----- Java Code -----------------------------------------------------------------------------------------------------------------
    // Clear
    // Description:
    // This function clears all the data in the stop tables in the database
    // given in the connection.
    public static void Clear (Connection connection)
    Statement statement;
    try
    statement = connection.createStatement();
    statement.executeUpdate("DROP INDEX stops_index");
    statement.executeUpdate("DELETE stops");
    statement.close();
    catch (SQLException e)
    System.err.println("SQLExcpetion (Stop.Clear()): " + e.getMessage());
    // Create_Indices
    // Description:
    // Create indices for stops table
    public static void Create_Indices (Connection connection)
    Statement statement;
    String sql_query;
    sql_query = "CREATE INDEX stops_index ON stops(location) " +
    "INDEXTYPE IS MDSYS.SPATIAL_INDEX";
    try
    statement = connection.createStatement();
    statement.executeUpdate(sql_query);
    statement.close();
    catch (SQLException e)
    System.err.println("SQLExcpetion (Stop.Create_Indices()): " + e.getMessage());
    // Insert
    // Description:
    // This function inserts this object into the stops table in the database
    // given in the connection.
    public void Insert (Connection connection)
    Statement statement;
    String sql_query;
    sql_query = "INSERT INTO stops VALUES ('" +
    stop_id + "', '" +
    address + "', " +
    "sdo_geometry(2001, null, sdo_point_type(" +
    location.x + "," +
    location.y + ",null), null, null)" +
    try
    statement = connection.createStatement();
    statement.executeUpdate(sql_query);
    statement.close();
    catch (SQLException e)
    System.err.println("SQLException (Stop.Insert()):" + e.getMessage());
    Message was edited by: loos to include the changes proposed by the second poster.

    Hi,
    Thanks for trying but changing those items for the specific failing queries didn't seem to help. Though you do seem to be right about the internal/external polygon problem, so I changed it all my other queries to see if they would fail (that way things would at least be consistent), but it doesn't seem to make a difference. All my old failing quries still fail and my working ones still work. I also changed the co-ordinates as you specified and still have no changes (unless of course the results changed, but right now I'm just looking for queries that compile and run, the results don't matter yet).
    Maybe this will help, I'll give you guys both sets of data, one that works and one that doesn't and maybe you can see a problem in the data that I'm just missing or too ignorant to see. The data is simply comma seperated values that I parse into the required fields in the order (id, description, x, y).
    So far, the only reason I've been able to find that the non-working data doesn't work is because there are more than 31 rows. I started taking records out of the stops table in a binary search sort of pattern. If I take out stops 100-115 (resulting 29 records) all the queries work, if I take out stops 100-107 (resulting in 36 records) it doesn't work. If I take out 109-115 (resulting in 35 records) it doesn't work. If I take out 1-11 (resulting in 32 records) it doesn't work. If I take out 1-12 (resulting in 31 records) it does work. Here's a table
    Take out Stops ---- records left -- Works?
    s1-s11 ------------ 32 ------------ No
    s1-s12 ------------ 31 ------------ Yes
    s100-s115 --------- 29 ------------ Yes
    s100-s107 --------- 36 ------------ No
    s109-s115 --------- 35 ------------ No
    Thanks again for checking this out,
    Brad
    ------- Working Data ---------------------------------------------------------------------------------------
    (Student_id, Department, x, y)
    Student_1,Computer Science ,296,131
    Student_2,Social Science,130 ,279
    Student_3,Mechanical Engineering ,392,180
    Student_4,Electrical Engineering ,342,322
    Student_5,Computer Science ,165,490
    Student_6,Scicology ,393,533
    Student_7,Physical Therapy ,590,616
    Student_8,Civil Engineering ,165,640
    Student_9,English ,360,412
    Student_10,Economy ,89,32
    Student_11,Computer Science ,26,117
    Student_12,Social Science,430 ,291
    Student_13,Mechanical Engineering ,382,80
    Student_14,Electrical Engineering ,542,222
    Student_15,Computer Science ,154,290
    Student_16,Scicology ,493,323
    Student_17,Physical Therapy ,290,426
    Student_18,Civil Engineering ,65,230
    Student_19,English ,300,412
    Student_20,Economy ,44,292
    Student_21,Computer Science ,146,431
    Student_22,Social Science,405 ,179
    Student_23,Mechanical Engineering ,192,480
    Student_24,Electrical Engineering ,412,202
    Student_25,Computer Science ,265,49
    Student_26,Scicology ,33,273
    Student_27,Physical Therapy ,186,216
    Student_28,Civil Engineering ,365,600
    Student_29,English ,309,42
    Student_30,Economy ,415,392
    ------- Non Working Data ---------------------------------------------------------------------------------
    (Stop_id, Address, x, y)
    s1, 2341 Portland,377,64
    s2, 24th St. / Hoover St.,308,22
    s3, 2620 Monmouth Ave.,272,138
    s4, 2632 Ellendale Pl.,128,110
    s5, 2726 Menlo Ave.,85,231
    s6, 2758 Menlo Ave.,84,124
    s7, 28th St. / Orchard Ave.,183,236
    s8, 28th St. / University Ave.,414,308
    s9, 30th St. / University Ave.,391,352
    s11, 34th St. / McClintock St.,180,458
    s12, 36th Pl. / Watt Way,176,622
    s13, Adams Blvd. / Magnolia Ave.,218,87
    s14, BG Mills Apts.,23,637
    s15, Cardinal Gardens Apts.,156,389
    s16, Centennial Apts.,373,126
    s17, Chez Ronee Apts.,446,414
    s18, City Park Apts.,70,323
    s19, Dental School,219,478
    s96, Founders Apts.,373,192
    s97, Hillview Apts.,412,214
    s98, House of Public Life,531,303
    s99, JEP,304,523
    s100, Kerchoff Apts.,473,272
    s101, Leavey Library,370,559
    s103, McClintock St. / Childs Way,129,553
    s104, Mt. St. Marys College,565,127
    s105, Pacific Apts.,398,240
    s107, Parking Center,525,652
    s109, Parkside,78,651
    s110, Severance St. / Adams Blvd.,435,202
    s111, Research Annex,492,776
    s112, Sierra Apts.,352,230
    s113, Sunset Apts.,267,278
    s114, Terrace Apts.,156,280
    s115, Troy East Apts.,402,397
    s116, University Regents Apts.,182,181
    s117, Watt Way / 36th Pl.,176,622
    s119, Watt Way / Bloom Walk,158,653
    s120, Windsor Apts.,257,236
    s121, Zemeckis Center,476,474
    s137, Gate #2,321,715
    s138, 24th St. / Toberman St.,377,64

  • How to save an n-ary tree of nodes to and from an xml file

    Hello,
    I am trying to represent a n-ary tree of nodes in xml.
    More accurately, I am trying to save/instantiate a
    tree of nodes to-from an xml file.
    How do I represent the parent-child relationships?
    Java: (simplified)
    class Node {
    Arraylist childNodes;
    Node parent;
    XML:
    From what I have been learning about XML,
    DTD:
    <?xml version="1.0" ?>
    <!DOCTYPE acd
         <!ELEMENT Node (childNodes, parent)>
         <!ATTLIST Node id ID #REQUIRED>
         <!ELEMENT childNodes (Node*)>
         <!ELEMENT parent (Node?)>
    ]>
    Qs:
    1) How do I represent the relationships? What would
    normally be a reference in Java, how do I represent in
    XML?
    2) Do I use ID, IDREF? I have been trying to find some
    examples to learn how. i.e. Does the IDREF, ID
    automatically become an in-memory reference (or pointer)?
    3) Is it preferable to use XML schema?
    thanks,
    Anil Philip
    Olathe, KS
    for good news go to
    http://members.tripod.com/goodnewsforyou/goodnews.html

    I downloaded XML Spy and used it to correct my earlier schema.
    Qs:
    In the instance document xml file;
    1) How would one display the parent node?
    2) If a child has a reference to a parent node as in the schema below, how can one know that the references are the same?
    i.e. when the parent node is first declared and when it is referred to by the child.
    Perhaps this raises a larger question - how does XML handle recursive references?
    <?xml version="1.0" encoding="UTF-8"?>
    <xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" targetNamespace="http://juwo.com/acd" xmlns="http://juwo.com/acd" elementFormDefault="qualified" attributeFormDefault="unqualified">
         <xs:annotation>
              <xs:documentation>ACD nodes. juwo LLC 2005</xs:documentation>
         </xs:annotation>
         <xs:complexType name="Node">
              <xs:sequence>
                   <xs:element name="parent" type="Node" minOccurs="0"/>
                   <!-- Node[] childNodes -->
                   <xs:element name="childNodes" type="ListOfNodes"/>
                   <!-- String data -->
                   <xs:element name="data" type="xs:string"/>
              </xs:sequence>
              <!-- Node parent -->
         </xs:complexType>
         <xs:complexType name="ListOfNodes">
              <xs:sequence>
                   <xs:element name="i" type="Node" minOccurs="0" maxOccurs="unbounded"/>
              </xs:sequence>
         </xs:complexType>
    </xs:schema>

  • What is the non-recursive stack based equivalent of this function?

    what is the non-recursive stack based equivalent of this function?
         static void _try (int n)
              int i; if (n==4) print(); else for (i=0; i<4; i++) if (is_free(i,n)) {
                   x[n] = i;
                   _try(n+1);
         }

    It goes infinite no output. Thanks though.
    public class CopyOfDamen { // x[i] = x coordinate of queen in row i.
         static int N = 4; static Stack stack = new Stack(); static int [] x = new int[8]; public static void main(String [] par) { _try(); }
         // prints field
         static void print ()
              int i,j;
              System.out.print ("+----------------+\n");
              for (i=0; i<8; i++) {
                   System.out.print ("|");
                   for (j=0; j<8; j++)
                        if (j==x) System.out.print ("<>"); else System.out.print (" ");
                   System.out.print ("|\n");
              System.out.print ("+----------------+\n\n");
         // tests, whether (ix, iy) is beaten by queens 0...(iy-1)
         static boolean is_free (int ix, int iy)
              int i;
              for (i=0; i<iy; i++)
                   if ((x[i]==ix) || (Math.abs(x[i]-ix)==Math.abs(i-iy))) return false;
              return true;
         // tries to place queen n on row n
         static void _try () {
              int i = 0, n = 0;
    call:
              for(;;) { // forever
                   if (n == N) {
                        print();
                   } else {
                        for (;i < N; i++) {
                             if (is_free(i,n)) {
                                  x[n] = i;
                                  System.out.print(x[n] + " ");
                                  n++;
                                  stack.push(i);
                                  i = 0;
                                  continue call; // call _try (but first save state and initiate new state)
                        } System.out.println();
                   // _try returns (check termination criterion and restore state)
                   n--;
                   if (n < 0) break; // terminate
                   i = stack.pop();
    } class Stack {
         int StackSize = 32, top = 0; int [] stack = new int[StackSize]; public Stack() {} void push(int x) { if (top < StackSize) stack[top++] = x; } int pop() { if (top >= 1) return stack[--top]; return -1; }

  • Non-recursion-based regex

    I'm doing some heavy duty very special case regexing. If fact I have to build them programatically as the actual regular expressions can grow to over 60,000 characters in length.
    I'm doing this in 1.3.1 and have tried a couple free/open source regex packages. As one might imagine, I get StackOverflowErrors very often in every package I've tried.
    If this is such a problem with regular expressions, it seems someone would have created a Java regexp package that doesn't rely so heavily on recursion. (In fact people have, in other languages, I just haven't found one in Java).
    Anyway, my first question is: is there a Java non-recursion-based regex package out there?
    I know I can increase the stack size, but to what?! I build my regexs on the fly, and the data they operate on is also generated on the fly.
    I think an OutOfMemoryError with a non-recursive implementation would be a lot less likely that a StackOverFlowError. ???
    It's Saturday (as you can see) and it looks more and more like I may have to write/port a regex package that fits the bill. This is really a pain.
    Another possibility is to use GNU Kawa (which implements proper tail recursion) to compile a Scheme regexp implementation into something I can use from Java. This seems really convoluted.
    Any ideas?

    Indeed, a 60,000 char regex is, to be blunt,
    ridiculous. There has to be another approach to
    whatever problem you are solving (is it biological in
    nature, perchance?). It's pattern recongition of structures of objects.
    My problem is that what I would REALLY like to do boils down to "regular expressions" over an 2-dimentional array of arbitrary objects, not characters.
    As a completely inane example: 3 Strings who's length is between 7 and 19 that don't start with "foo" or "bar", followed by any number of objects implementing Runnable but not Comparable.
    I started doing this from scratch, but I thought a faster way to get things done was to cheat.
    So I created a system to translate the objects I'm interested in to a "compact" String representation, right now it's about 32 characters long. I can specify properties I'm looking for with this representation, or specify I don't care with '.' values in the fields I don't care about. So for example a lowercase e in a particular index represents non-editable, uppercase means editable, '.' means I don't care. Some field/properties require multiple characters to represent them.
    Now the patterns I'm looking for are in a 2 dimensional array of objects.
    When you start multiplying hundreds of objects by hundreds of objects by 32 characters per object ... You get a pretty big regex.
    Another option I've started is custom, from scracth "Java Object Regular Expressions" or JOREs as I like to call them (I already started coding this and needed a package name).
    (Does anything like this already exist? I haven't found it.)
    Anyway, 60,000 is bordering on worst case scenarios. It could happen. 7000-ish is a more realistic average I'd expect, but it doesn't make worst cases go away.
    It seems even in many smaller cases I get a StackOverflowError, but there are probably more nested .{,}[^]+* type things in those to make them more complex.

  • CLOSED- Recursive Tree with Recursive Table and seperate Relationship table

    Hi All,
    I am trying to achieve a adf recursive tree with recursive table but relationships are stored in separate table like
    Table A:
    id name
    1 Val1
    2 Val2
    3 Val3
    4 Val4
    5 Val5
    Table B:
    fromid rel_type toid
    1 Parent-of 2
    2 Parent-of 3
    3 Parent-of 4
    1 Parent-of 5
    I did lots of reading from forum and various posts but couldn't make it work.
    Any suggestion what would be best approach and/or sample code for this ?
    Thanks

    I think that you can get this done by defining a VO that fetches all the top level nodes and have a view link to a VO that has all the details with a self recursive viewlink
    Query for the top level
    Select A.id, A.name
    from A
    Where A.id not in (select disctinct toid from B)
    Query for the detail level
    Select A.id, A.name, B.from, B.to
    from A,b
    where a.id = b.toid;
    ViewLink is going to be:
    detail.from=master.id
    and another viewlink for the recursive relationship
    detail.from=detail.to

  • Let us discussion "non recursive with clause" usage

    I think there are 3 "non recursive with clause" usage.
    My question is do you know more "non recursive with clause" usage ?

    Another option is to use it to materialize remote data on the fly. Especially in combination with the materialize hint.
    I think I used this tecnique once, but can't find the proper example anymore. Very simplified it could looked like this:
    with fetchData as (Select /*+materialize */ * from myremoteTable@databaselink where status = 'CURRENT')
    select *
    from fetchdata r
    full outer join localData l on r.id = r.id
    where l.status = 'CURRENT'
    ;From 11g onwards: use the with clause to create better column names in larger select from dual combinations.
    Not sure with that results in a suitable use case.
    So instead of
    with orders as
    (select 1 id , 173 order#, 'John' customer, 'America' region from dual union all
      select 2 id , 170 order#, 'Paul' customer, 'UK' region from dual union all
      select 3 id , 240 order#, 'Hans' customer, 'Europe' region from dual union all
      select 4 id , 241 order#, 'Francois' customer, 'Europe' region from dual )
    select * from orders;you can now write
    with
    orders (id, order#, customer,region) as
    (select 1 , 173 , 'John' , 'America' from dual union all
      select 2 , 170 , 'Paul' , 'UK' from dual union all
      select 3 , 240 , 'Hans' , 'Europe' from dual union all
      select 4 , 241 , 'Francois' , 'Europe' from dual )
    select * from orders;THis makes it a little easier to create tase data useing some excel sheet I guess.

  • Recursive node and Non Recursive node

    Hi,
    What is the difference between Recursive node and Non Recursive node ?
    Thanks,
    Teja

    Hi Teja
    Recursive node
    If you wish to represent a recursive data structure within the context, a recursive node is the correct node to use. The simplest example of recursive data within a hierarchical structure is a file system. A dictionary can contain either files or subdirectories. This definition is then repeated for each subdirectory level down the hierarchy.
    Within the context, a recursive node is a special node that has only two properties: name and repeatedNode. As with any context node, a recursive node must itself name, but the repeatedNode property is where the recursion is defined. This property holds a reference to some parent node and indicates that, at runtime, the location of the recursive node will be occupied by a node of the type indicated in the repeatedNode property.
    You should think of a recursive node as a design time placeholder used to indicate a node will be created at this location at runtime, and will be of the type named in the repeatedNode property.
    The node name identified by repeatedNode must lie on the direct path back to the context root node.
    When a recursive node is created at runtime it always created as a non-singleton node. This is a hard-coded feature and cannot be changed.
    Non recursive node is opposite to recursive node
    Regards
    Ruturaj

  • Create a tree with recursive call for sub-rows

    Hello,
    I would like to create a generated menu dynamically created from values returned by sql.
    Structure is as follow :
    Menu
      |
      +-- MenuItem <--+
             |        |
             +--------+I can't know the maximum depth of the menu.
    How can I create a dynamic tree for ADF to display a tree or a hierarchical view properly without having to define a ViewLink / level ? (i.e. without hardcoding the maximum depth)
    I created a simple Application Module with VO:
    MenuVO
      + MenuItemVO (using VL1 between MenuItem and Menu)
          + SubMenuItemVO (using VL2 between MenuItem and MenuItem, father / child link)Using the Oracle BC Navigator to test this, I can see that a dynamic tree is available, how can I have it in a JSP page ?
    Using the hierarchy viewer component it's possible, but how can I do this with an ADF Tree ?

    You can easily create a recursive tree level rule on the MenuItemVO via a parent/child view link (get rid of SubMenuItemVO). Look at this example http://www.oracle.com/technetwork/developer-tools/adf/learnmore/32-tree-table-from-single-vo-169174.pdf
    The only difference is your recursion is going to be at MenuItemVO level.
    Edited by: 948181 on 2012/07/31 4:07 PM

Maybe you are looking for

  • Ichat deleted itself. Now I restored it and it says I can't use it.

    So the other day I opened my computer after coming back from a trip. I had just used ichat the night before I left, but then I get home and the application is nowhere to be found on my computer. The icon is on the dock but a (?) just pops up over the

  • Mapping parts of a simple message array

    Hi, Suppose i have the flowing MT: Root: 1..1   Item: 1..Unbound     Row: 1..1 Which contain the following message: <Root>   <Item>     <Row>My flat file header...</Row>   </Item>   <Item>     <Row>My flatfeet row 1...</Row>   </Item>   <Item>     <R

  • PDF Export and CID Encoding criteria

    I have read that, when a document is exported to PDF, only certain types of fonts are CID encoded. What criteria is used ?? Thanks. Jorge

  • HT1338 How do I upgrade my OS X?

    I'm running OS X 10.5 but when I go to the Apple menu and select Software Update it says my Mac is up to date...how do I upgrade my OS X? Lazar

  • "client node" on desktop

    After updating to Mac OS X 10.6 a new file "client node" appeared on my desktop. This file cannot be moved or delete. Does anybody know what this file is? Thanks in advance !!!