C++: Binary tree search and modification

Discussion in 'OT Technology' started by et3rnul, Feb 19, 2008.

  1. et3rnul

    et3rnul OT Supporter

    Joined:
    Mar 15, 2006
    Messages:
    308
    Likes Received:
    0
    Location:
    SoCal
    How do I implement a class that searches through a binary tree and modifies a node's field? For example, each node has an id and name field, I want to search for the id, and then modify the name belonging to that id. I want to be able to make a method that can be reused to modify other fields belonging to that node.

    My first though was something like this (psuedo)

    void setField(int id, string fieldname)
    {
    Node *n = lookup(id);
    n->fieldname = "some value";
    }

    lookup(int id)
    {
    // find the node in the tree recursively
    return pointer to node?
    }

    Can this be done? New to C++, still trying to get used to pointers, references, etc. Not asking for code, just the idea behind it.
     
    Last edited: Feb 19, 2008
  2. Sexual Vanilla

    Sexual Vanilla New Member

    Joined:
    May 23, 2005
    Messages:
    6,305
    Likes Received:
    0
    Location:
    South Carolina
    Can it be done with C++? Absolutely...as I have done it before for a project in one of my programming classes. Do I remember what I did? No.
     
  3. deusexaethera

    deusexaethera OT Supporter

    Joined:
    Jan 27, 2005
    Messages:
    19,712
    Likes Received:
    0
    Check the current node. If it's the node you're looking for, modify it and return true. Otherwise, check the node's left child by calling the same function recursively; if the return value is true, return true; otherwise, check the right child. If the return value is true, return true, otherwise return false.
     
  4. et3rnul

    et3rnul OT Supporter

    Joined:
    Mar 15, 2006
    Messages:
    308
    Likes Received:
    0
    Location:
    SoCal
    Right, but I'd like the modification to happen from the method that called the recursive method the first time. That way I could have one method that modifies one field in the node, and another method that modifies a second field in the node, both using the lookup method to get to the node.
     

Share This Page