2012年1月7日 星期六

Binary Search Tree & Inorder Traversal

以迴圈方式建立binary search tree



#include <stdio.h>
#include <stdlib.h>

struct tree {
    int value;
    struct tree * left;
    struct tree * right;
};

enum LR {LEFT, RIGHT};

typedef struct tree Tree;
typedef Tree * TreePtr;

void insertNode(TreePtr * root, int value)
{
    enum LR dir;
    TreePtr newPtr, current, previous;

    newPtr = malloc(sizeof(Tree));

    if (newPtr != NULL)
    {
        newPtr->value = value;
        newPtr->left = NULL;
        newPtr->right = NULL;
        if (*root == NULL)
            *root = newPtr;
        else
        {
            current = *root;
            while (current != NULL)
            {
                if (value < current->value)
                {
                    previous = current;
                    current = current->left;
                    dir = LEFT;
                }
                else if (value > current->value)
                {
                    previous = current;
                    current = current->right;
                    dir = RIGHT;
                }
            }

            if (dir == LEFT)
                previous->left = newPtr;
            else
                previous->right = newPtr;
        }
    }
}

void inOrder(TreePtr * root)
{
    if (*root == NULL)
        return;
    inOrder(&((*root)->left));
    printf("%d ", (*root)->value);
    inOrder(&((*root)->right));
}

int main(void)
{
    int num[11] = {3, 12, 9, 102, 12, 21, 10, 1, 6, 8, 91};
    int i;
    TreePtr root = NULL;

    for (i = 0; i < 11; i++)
        insertNode(&root, num[i]);
    inOrder(&root);

    return 0;
}

沒有留言:

張貼留言