b00k3r
b00k3r

Reputation: 11

Search for an item in an n-ary tree

I have a tree n-ary composed in this way:

struct n_tree{
    struct list *adj;    
};

struct list{
    struct n_tree *child;
    struct list *next;
    int key;
};

How i can search an item? I have implemented this function, but it does not work... Thanks!

struct list *find(struct list *root, int key){
    if(root){
        find(root->next,key);
        if (root != NULL){
            if(root->key == key){
                return root;
            }
            else if(root->child != NULL){
                return find(root->child->adj,key);
            }
        }
    }
}

Upvotes: 1

Views: 5547

Answers (3)

CiaPan
CiaPan

Reputation: 9570

Here is (possibly the smallest) modification of your code to achieve your goal:

struct list *find(struct list *root, int key){
    for(; root != NULL; root = root->next){   // scan the siblings' list
        if(root->key == key)                  // test the current node
            return root;                      // return it if the value found

        if(root->child != NULL) {             // scan a subtree
            struct list *result = find(root->child->adj, key);
            if(result)                        // the value found in a subtree
                return result;                // abandon scanning, return the node found
        }
    }
    return NULL;                              // key not found
}

Upvotes: 0

Picodev
Picodev

Reputation: 556

It seems that what you are trying to implement is a n-ary tree with a binary implementation (first child, right sibling).

It's more obvious with other namings :

struct n_tree{
  struct list *root;    
};

struct tree_node{
    int key;
    struct tree_node *first_child;
    struct tree_node *right_sibling;
};

A recursive search function returning the node with the key key or NULL if no node is found could be :

struct tree_node *find_node(struct tree_node *from, int key){
  // stop case
  if (from==NULL) return NULL;
  if (from->key==key) return from;
  // first we'll recurse on the siblings
  struct tree_node *found;
  if ( (found=find_node(from->right_sibling,key) != NULL ) return found;
  // if not found we recurse on the children
  return find_node(from->first_child, key);
}

If you need a wrapper function with a n_tree argument :

struct tree_node* find(struct n_tree* tree, int key) {
  return find_node(tree->root, key);
}

Upvotes: 1

unwind
unwind

Reputation: 399803

Before looking at the children, you need to look at the local node, since that's how you actually find things and end the recursion.

Also, doing a recursive call and ignoring the return value is pointless (unless there's an "out-parameter", which there isn't here). So don't do that.

Upvotes: 0

Related Questions