#include #include "bintree.h" /* * bintree_add - Add to tree * * Adds a node to a sorted tree. If the new node is already found from * the tree, the existing node is returned and the new node is not * added. If new node is not found, the new one is added and the tree * is kept sorted. */ struct bintree *bintree_add(struct bintree *tree, struct bintree *new, struct bintree_ops *ops) { int ret; if (tree == NULL) return new; ret = ops->compare(tree, new); if (ret < 0) { if (tree->left) return bintree_add(tree->left, new, ops); tree->left = new; return new; } if (ret > 0) { if (tree->right) return bintree_add(tree->right, new, ops); tree->right = new; return new; } return tree; } /* * bintree_find - Find a node from a tree. * * If node is found, pointer to the node is returned. If no node is * found, null is returned. */ struct bintree *bintree_find(struct bintree *tree, struct bintree *new, struct bintree_ops *ops) { int ret; if (tree == NULL) return NULL; ret = ops->compare(tree, new); if (ret < 0) { if (tree->left) return bintree_find(tree->left, new, ops); return NULL; } if (ret > 0) { if (tree->right) return bintree_find(tree->right, new, ops); return NULL; } return tree; } /* * bintree_walk - walk through a binary tree from left to right * * Returns the number of nodes in the tree */ int bintree_walk(struct bintree *tree, struct bintree_ops *ops) { int count = 0; if (tree->left) count += bintree_walk(tree->left, ops); if (ops->callback) ops->callback(tree, ops); count++; if (tree->right) count += bintree_walk(tree->right, ops); return count; }