CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 2 of 2
  1. #1
    Join Date
    Apr 2008
    Posts
    1

    Inserting a structured file into a binary tree

    Heya, I'm having a spot of trouble trying to place a structured file into a binary tree. I'll try to explain what I'm trying to accomplish as best as I can.

    I have a file, containing a binary tree structure that looks like this:
    Code:
    [(x,y)[...][...]]
    example:
    Code:
    [(6,2)[(4,1)[(1,1)[][]][(5,4)[][]]][(9,3)[][]]]
    after inserting into a tree should look like this:
    Code:
                 (6,2)
                /       \
          (4,2)       (9,3)
           /   \
     (1,1)  (5,4)
    Basically, the ordered pairs are what I put into the tree and [] means an empty tree.

    The problem is that I can sorta form an algorithm in my head, but I don't know how to go about coding this. So far, I've tried putting the structure into a character array and going one by one to search for the numbers, however I don't know how to set it up so that I can recursively build my tree.

    Can anyone help me? I'm not looking for a detailed program, but just a simple setup to point me in the right direction.

    Thank you for your time

  2. #2
    Join Date
    Mar 2007
    Location
    Montreal, Quebec, Canada
    Posts
    185

    Re: Inserting a structured file into a binary tree

    You can use a recursive parser, like this (pseudo-code):
    Code:
    function parse(input, i)
        if input[i] = ']' return null
    
        node = new node
        node.value = parse an (x,y)
        accept a '['
        node.left = parse(input, position after the '[')
        accept a ']'
        accept a '['
        node.right = parse(input, position after the '[')
        accept a ']'
        return node
    end
    
    tree = parse(the input file)
    The accept call would throw an error if the next character was something else besides what you passed to it, otherwise it would increment i.

    Hope this helps.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured