Non binary tree implementation in C

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • hurray
    New Member
    • Jul 2008
    • 3

    #1

    Non binary tree implementation in C

    If somebody has a non binary tree(an example, form shown below) implementation in C, could you pass it along. Sample tree of the form

    ___________ A___________
    | | |
    ____ M__ __N X
    | | | | |
    E F G L P

    Generic implementation would help.

    Thanks
  • Laharl
    Recognized Expert Contributor
    • Sep 2007
    • 849

    #2
    You can't really do generics in C, since there's no templates. That said, the easiest way to implement a variable-arity tree is to use two pointers in each node, one to the first child, one to the next sibling.

    [CODE=c]
    struct tree_node {
    int data;
    struct tree_node* first_child; //Points to the first node on the next level down
    struct tree_node* next_sibling; //Points to the next node on the same level
    };
    [/CODE]

    Comment

    • hurray
      New Member
      • Jul 2008
      • 3

      #3
      Originally posted by Laharl
      You can't really do generics in C, since there's no templates. That said, the easiest way to implement a variable-arity tree is to use two pointers in each node, one to the first child, one to the next sibling.

      [CODE=c]
      struct tree_node {
      int data;
      struct tree_node* first_child; //Points to the first node on the next level down
      struct tree_node* next_sibling; //Points to the next node on the same level
      };
      [/CODE]

      Do you have a C implementation for the kind of tree i pointed.

      Comment

      • hurray
        New Member
        • Jul 2008
        • 3

        #4
        Originally posted by hurray
        Do you have a C implementation for the kind of tree i pointed.

        A
        / \ \
        B C D
        / \
        E F

        Looks like thre tree had got all messed up. here is a better representation.

        Comment

        • Laharl
          Recognized Expert Contributor
          • Sep 2007
          • 849

          #5
          You can use that struct as the nodes of the tree by setting the pointer variables within to make that tree. I'm not going to write the code for you, I've given you everything else already.

          Comment

          Working...