/* * Copyright (C) 2010 Timo Kokkonen * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ #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; }