Thread: Binary Search Tree sort

Threaded View

Previous Post Previous Post   Next Post Next Post
  1. #1
    Registered User
    Join Date
    Dec 2017
    Posts
    24

    Binary Search Tree sort

    Hey, I'm working on a BST Sort and I don't know why this code is not running the way I want. Actually, I have no compilation errors neither warnings, it's just doesn't match with the attended result

    Code:
    #include <stdio.h>
    #include<stdlib.h>
    
    
    struct Node{
        int value;
        struct Node *left, *right;
    };
    
    
    struct Node *newNode(int value){
        struct Node *node = malloc(sizeof *node);
        node->value = value;
        node->left = NULL;
        node->right = NULL;
        return node;
    }
    
    
    struct Node *insert(struct Node *node, int value){
        if(node == NULL)
             return newNode(value);
        if(value < node->value)
            node->left = insert(node->left, value);
        else if (value > node->value)
            node->right = insert(node->right, value);
        return node;
    }
    
    
    void collect(struct Node *root, int T[], int i){
        if(root != NULL){
            collect(root->left, T, i);
            T[i++] = root->value;
            collect(root->right, T, i);
        }
    }
    
    
    void binary_tree_sort(int T[], int n){
        struct Node *root = NULL;
        root = insert(root, T[0]);
        int i;
        for(i = 1; i < n; i++)
            insert(root, T[i]);
        i = 0;
        collect(root, T, i);
    }
    
    
    int main(void){
        int TAB[] = {47, 39, 1, 45, 11};
        int n = sizeof(TAB)/sizeof(TAB[0]);
        binary_tree_sort(TAB, n);
        int i;
        for(i = 0; i < n; i++)
            printf("%d ", TAB[i]);
        return 0;
    }
    It should have returned 1 11 39 45 47
    However it returns the original array 47 39 1 45 11

    I must say that I'm a bit confused
    Last edited by ElPosto; 12-27-2017 at 06:23 PM.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Binary Search Tree-search method help?
    By shocklightning in forum C++ Programming
    Replies: 5
    Last Post: 03-25-2012, 10:57 PM
  2. binary search tree
    By angel34 in forum C Programming
    Replies: 0
    Last Post: 12-10-2010, 03:32 PM
  3. Replies: 0
    Last Post: 11-04-2006, 11:07 AM
  4. A Binary Search Tree of... Binary Search Trees...
    By SlyMaelstrom in forum C++ Programming
    Replies: 5
    Last Post: 12-10-2005, 02:12 PM
  5. Search Engine - Binary Search Tree
    By Gecko2099 in forum C Programming
    Replies: 9
    Last Post: 04-17-2005, 02:56 PM

Tags for this Thread