TreeNode *createBST( ListNode *node, int start, int end )
 {
     if( node == NULL ) return NULL;
     if( start>end ) return NULL;
     int mid = (start+end)/2;
     ListNode *current = node;
     for( int i = start ; i<mid; i++ )
     {
         current = current->next;
     }
     TreeNode *newNode = new TreeNode( current->val );
     newNode->left = createBST( node, start, mid-1);
     newNode->right = createBST( current->next, mid+1, end );
     
     return newNode;
 }
示例#2
0
void ex4_6() {
    std::cout << "ex4.6 \n";
    std::vector<int> in;
    for (int sample = 0; sample <  10; ++sample)
        in.push_back(std::rand() % 2000);
    std::sort(in.begin(), in.end());
    TreeNode<int>* node = createBST(in, 0, (int) in.size()) ;
    auto root = node;
    TreeNode<int>* rightmost = root;
    std::cout << "root.value=" << root->value << ", node.value=" << node->value << ", rightmost.value=" << rightmost->value << std::endl;
    rightmost = rightmost->right;
    rightmost = rightmost->right;
    auto next = getNextNode(rightmost);
    std::cout << "next node of node "  << rightmost->value << " is " << (next ? next->value : -1 ) << std::endl;   //    std::cout << " sample size=" << in.size() << ", max height = " << height << ", log(size)=" << log2(in.size()) << std::endl;
    //std::cout << "is it a BST? " << checkBST(node);
    auto lists = createLists(node);
    for (int depth = 0; depth < lists.size(); ++depth) {
        std::cout << " level " << depth << ": ";
        for (auto elem : lists[depth]) {
            std::cout << elem->value << ", ";
        }
        std::cout << std::endl;
    }
   
    std::cout << "next node of node "  << node->value << " is " << getNextNode(node)->value << std::endl;
    node = node->right;
    std::cout << "next node of node "  << node->value << " is " << getNextNode(node)->value << std::endl;
    node = node->left;
    std::cout << "next node of node "  << node->value << " is " << getNextNode(node)->value << std::endl;
    node = node->left;
    std::cout << "next node of node "  << node->value << " is " << getNextNode(node)->value << std::endl;
}
示例#3
0
int main(){
	printf("Creating a binary search tree\n");
	struct BSTNode* root =NULL;
	root = createBST(root);
	printf("\nPrinting LeafNodes \n");
	listLeaves(root);	
}
示例#4
0
TreeNode<T>* createBST(const std::vector<T>& sorted, int first, int last) {
    int rootInd = (last - first) / 2 + first;
    if (last == first + 1) // base case
        return new TreeNode<T>(sorted[first], nullptr, nullptr);
    TreeNode<T>* leftPtr = nullptr;
    if (first != rootInd)
        leftPtr = createBST(sorted, first, rootInd);
    TreeNode<T>* rightPtr = nullptr;
    if (rootInd + 1 != last)
        rightPtr= createBST(sorted, rootInd + 1, last);
    TreeNode<T>* res = new TreeNode<T>(sorted[rootInd], leftPtr, rightPtr);
    if (leftPtr)
        leftPtr->parent = res;
    if (rightPtr)
        rightPtr->parent = res;
    return res;
}
示例#5
0
int main ()
{
	Node* root = createBST(std::vector<int>(2,3,4,5,6,7));

	assert(validateBST(root));

	return 0;
}
示例#6
0
void ex_4_8() {
    std::vector<int> in;
    //seed48(2018);
    for (int sample = 0; sample <  20180000; ++sample)
        in.push_back(std::rand() % 200);
    std::sort(in.begin(), in.end());
    TreeNode<int>* node = createBST(in, 0, (int) in.size()) ;
    auto root = node;
    std::cout << "subtree " << (findSubtree(root, root->left) ? " exists " : " doesn't exist ") << std::endl;
}
示例#7
0
void ex4_5() {
    std::cout << "ex4.5 \n";
    std::vector<int> in;
    for (int sample = 0; sample < std::rand() % 10000; ++sample)
        in.push_back(std::rand() % 20);
    std::sort(in.begin(), in.end());
    auto node = createBST(in, 0, (int) in.size()) ;
//    std::cout << " sample size=" << in.size() << ", max height = " << height << ", log(size)=" << log2(in.size()) << std::endl;
    std::cout << "is it a BST? " << checkBST(node);
}
示例#8
0
//To add a new node to the tree
void createBST(node **r,int value)
{
    //allocating memory and assigning value
    if(*r==NULL)
    {
        *r=(node*)malloc(sizeof(node));
        (*r)->data=value;
        (*r)->left=NULL;
        (*r)->right=NULL;
        return;
    }
    else    //comparing the value with the value in the node
    {
        if((*r)->data > value)
            createBST(&(*r)->left,value);
        else
            createBST(&(*r)->right,value);
    }
}
示例#9
0
void ex4_3() {
    std::cout << "ex4.3 \n";
    for (int cases = 0; cases < 50; ++cases) {
        std::vector<int> in;
        for (int sample = 0; sample < std::rand() % 10000; ++sample)
            in.push_back(std::rand() % 20);
        std::sort(in.begin(), in.end());
        auto node = createBST(in, 0, (int) in.size()) ;
        auto height = getHeight(node) ;
        std::cout << " sample size=" << in.size() << ", max height = " << height << ", log(size)=" << log2(in.size()) << std::endl;
    }
}
示例#10
0
int main(int argc, char **argv)
{
	//Checking error
	if (argc < 2)
	{
		printf("usage: %s <input_filename>\n", argv[0]);
		return 0;
	}
	//Open file
	FILE *in = fopen(argv[1], "r");
	if (in == NULL) return 0;
	//Declaration of variable
	int i, size,level;
	//Scanning size from file
	fscanf(in, "%d", &size);
	//allocating memory for array
	int *array = malloc(size * sizeof(int));
	//Scanning number from the file
	for (i=0; i<size; i++)
		fscanf(in, "%d", &array[i]);
	//Declaring a node
	bst *root =NULL;
	//Creating BST
	root=createBST(array,size);
	//print in-order,pre-order,post-order tree traversal
	printf("Creating Binary Search Tree...\n");
	printf("In-order traversal: "); 
	printInorder(root); 
	printf("\n");
	printf("Pre-order traversal: ");
	printPreorder(root);
	printf("\n");
	printf("Post-order traversal: ");
	printPostorder(root);
	printf("\n");
	//Sort arrat
	sort(array,size);
	//Creatin binary tree with minimum level
	root=createMinBST(array,0,size-1);
	//printing BST
	printf("Minimum Height BST\n");
	printTree(root);
	//Bonus
	printf("Bonus.Please enter level of the tree:");
	scanf("%d",&level);
	if(level>height(root))
	printf("\nThe maximum height of this tree is %d",height(root));
	else
	printGivenLevel(root,level);

 return 0;
}
示例#11
0
int main(int argc, char *argv[]){

  //check command line arguments
  if(argc != 2){
    printf("usage: ./a.out <input_filename>");
    exit(0);
  }
  
  //open the file
  FILE* input = fopen(argv[1],"r");
  if(input == NULL){
    printf("File not found");
    exit(0);
  }

  bst* root = NULL; 
  int i = 0; 
  int size = 0;
  
  
  fscanf(input,"%d",&size);

  int *a = (int *)malloc(sizeof(int)*size);//create the array
  
  for(i=0;i<size;i++){
    fscanf(input,"%d",&a[i]);
  }
  
  close(input); //close file

  //printout the different ways
  printf("Creating Binary Search Tree\n");
  root = createBST(a,size);
  printf("In-Order traversal: ");
  printInorder(root); 
  printf("\nPre-Order traversal: ");
  printPreorder(root);
  printf("\nPost-Order traversal: ");
  printPostorder(root);

  printf("\n\nMinimum Height BST\n");
  sort(a,size);

  root = createMinBST(a,0,size-1);
  
  printTree(root);

  free(a); //free mem
  return 0;

}
 TreeNode *sortedListToBST(ListNode *head) {
     // Start typing your C/C++ solution below
     // DO NOT write int main() function
     //1. go the medium of the sortedlist, put 
     //create bst root based on this node
     //2. create BST left using head to medium
     //create BST right using medium+1 to end 
     //complexity O(nlogn );
     if( head == NULL ) return NULL;
     
     int len = getLength( head );
     TreeNode *newNode = createBST( head, 0, len-1 );
     return newNode;
 }
示例#13
0
int main(int argc, char **argv)
{
	if(argc < 2)
	{
		printf("usage: %s <input_filename>/n", argv[0]);
		return;
	}

	FILE* input = fopen(argv[1], "r");
	if (input == NULL)
		return;

	int i, size;
	fscanf(input, "%d", &size);
	int array[size];

	for(i=0; i<size; i++)
		fscanf(input, "%d", &array[i]);

	//Creates Binary Tree
	printf("Creating Binary Tree...\n");
	bst* root = createBST(array, size);

	//Printing Inorder Traversal
	printf("Inorder Traversal: ");
	printInorder(root);
	printf("\n");

	//Printing Pre-order Traversal
	printf("Pre-Order Traversal: ");
        printPreorder(root);
        printf("\n");

	//Printing Postorder Traversal
	printf("Postorder Traversal: ");
        printPostorder(root);
        printf("\n");

	//Printing the Binary Tree
	printf("\nMinimum Height BST\n");
	sort(array, size);
	root = createMinBST(array, array[0], array[size-1]);
	printTree(root);

	fclose(input);
	free(root);

	return 0;
}
示例#14
0
void ex4_4() {
    std::cout << "ex4.4 \n";
        std::vector<int> in;
        for (int sample = 0; sample < std::rand() % 10000; ++sample)
            in.push_back(std::rand() % 20);
        std::sort(in.begin(), in.end());
        auto node = createBST(in, 0, (int) in.size()) ;
        auto height = getHeight(node) ;
        std::cout << " sample size=" << in.size() << ", max height = " << height << ", log(size)=" << log2(in.size()) << std::endl;
    auto lists = createLists(node);
    for (int depth = 0; depth < lists.size(); ++depth) {
        std::cout << " level " << depth << ": ";
        for (auto elem : lists[depth]) {
            std::cout << elem->value << ", ";
        }
        std::cout << std::endl;
    }
}
示例#15
0
int main(){
	
	printf("Creating a binary search tree\n");
	struct BSTNode* root =NULL;
	root = createBST(root);
	struct BSTNode* prev = NULL;	
	struct BSTNode* temp=bst2dll(root,prev);
	struct BSTNode* temp1;
	while(temp!= NULL){
		printf("%d\n",temp->value);
		temp1 = temp;
		temp = temp->left;
		
	}	

	while(temp1!=NULL){
		printf("%d\n",temp1->value);
		temp1 = temp1->right;
	}
	return 0;
}
示例#16
0
int main(void)
{
	BST* contactBST; //NOT sure if these are right
	char userInput;
	int inputStatus;
	int quitStatus = 0;

	contactBST = createBST(compareWord);
	readFileBST(contactBST);
	while(quitStatus == 0){
		inputStatus = 0;
		while(inputStatus == 0){ //Looping until choice is entered correctly
			fflush(stdin);
			printf("Please select: (a) add, (d) delete, (l) lookup, or (q) quit: "); 
			scanf("%c",&userInput);
			if(userInput == 'a' || userInput == 'd' || userInput == 'l' || userInput == 'q'){
				inputStatus = 1;
			}
		}
		printf("Choice: %c",userInput);
		if(userInput == 'q'){ //User Quits
				quitStatus = 1;
		}
		else{
			if(userInput == 'a'){
				addName(contactBST);
			}
			else if(userInput == 'd'){
				//delete function here
			}
			else if(userInput == 'l'){
				//look up function here
			}
		}
	}

	contactBST = destroyBST(contactBST); //Not sure of this
	return 0;
}
示例#17
0
void ex4_7() {
    std::cout << "ex4.7 \n";
    std::vector<int> in;
    for (int sample = 0; sample <  10; ++sample)
        in.push_back(std::rand() % 2000);
    std::sort(in.begin(), in.end());
    TreeNode<int>* node = createBST(in, 0, (int) in.size()) ;
    auto root = node;
    TreeNode<int>* rightmost = root;
    std::cout << "root.value=" << root->value << ", node.value=" << node->value << ", rightmost.value=" << rightmost->value << std::endl;
    rightmost = rightmost->right;
    TreeNode<int>* oneToLeft = rightmost->left;
    rightmost = rightmost->right;
    
    
    auto next = getNextNode(rightmost);
    std::cout << "next node of node "  << rightmost->value << " is " << (next ? next->value : -1 ) << std::endl;   //    std::cout << " sample size=" << in.size() << ", max height = " << height << ", log(size)=" << log2(in.size()) << std::endl;
    //std::cout << "is it a BST? " << checkBST(node);
    auto lists = createLists(node);
    for (int depth = 0; depth < lists.size(); ++depth) {
        std::cout << " level " << depth << ": ";
        for (auto elem : lists[depth]) {
            std::cout << elem->value << ", ";
        }
        std::cout << std::endl;
    }
    
    //auto common = firstCommonAncestor(rightmost, oneToLeft);
    bool coversA = false; bool coversB = false;
    auto common = commonAncestorDescendRec(root, rightmost, oneToLeft, coversA, coversB);
    assert(common->value == 1709);
    coversA = false; coversB = false;
  //  common = firstCommonAncestor(root, rightmost);
    common = commonAncestorDescendRec(root, root, rightmost, coversA, coversB);
    assert(common == nullptr);
    std::cout << "common ancestor = " << (common ? common->value : 0) << std::endl;
}
示例#18
0
int main(void){
	contactData* dataList[MAX];
	BST* contactBST; //NOT sure if these are right
	char userInput;
	int inputStatus;
	int quitStatus = 0;
	

	contactBST = createBST(compareWord);
	readFileBST(dataList,contactBST);
	while(quitStatus = 0){
		inputStatus = 0;
		while(inputStatus == 0){ //Looping until choice is entered correctly
			printf("Please select from the following: (a) add, (d) delete, (l) lookup, or (q) quit:"); 
			scanf("%c",userInput);
			if(userInput == 'a' || userInput == 'd' || userInput == 'l' || userInput == 'q');
				inputStatus = 1;
			}
		if(userInput == 'q'){ //User Quits
			quitStatus = 1;
		}
		else{
			if(userInput == 'a'){
				//add function here
			}
			else if(userInput == 'd'){
				//delete function here
			}
			else if(userInput == 'l'){
				//look up function here
			}
		}
	}
	
	contactBST = destroyBST(contactBST); //Not sure of this
	return 0;
}
示例#19
0
int main()
{
	int arr[] = {10,3,5,2,9,100};
	int i, len, key;
	TreePointer bst, ret;
	
	len = arr_length(arr,int);
    
	//create tree using ADT
	bst = createBST(arr[0]);
	for(i=1; i <  len ; i ++)
		insert(bst,arr[i]);
    
	
	key = 2;
	ret = BSTsearch(bst,key);
	assert(ret!=NULL);
	assert(key==getBSTData(ret));
    
	//print all by order
	printSorted(bst);
    
	return 0;
}
示例#20
0
int main()
{
    node *root=NULL;
    int n;
    int num,i,value;
    while(1)
    {
        system("cls");
        printf("1. Create Binary Search Tree\n"
               "2. Delete a node\n"
               "3. inOrder Display\n"
               "4. Exit\n"
               "Enter Your Choice:- ");
        scanf("%d",&n);
        switch (n)
        {
            case 1:
                system("cls");
                printf("Enter the number of nodes you want to add: ");
                scanf("%d",&num);
                for(i=0;i<num;i++)
                {
                    printf("Enter the data for the %d node: ",i+1);
                    scanf("%d",&value);
                    createBST(&root,value);
                }
                printf("%d Nodes Added\n",num);
                getch();
                break;

            case 2:
                system("cls");
                printf("Enter the data of the node you want to Delete: ");
                scanf("%d",&value);
                del(&root,value);
                getch();
                break;

            case 3:
                system("cls");
                if(root==NULL)
                    printf("Empty Tree\n");
                else
                    inOrder(root);
                getch();
                break;

            case 4:
                system("cls");
                exit(0);

            default:
                system("cls");
                printf("\nWrong Selection");
                getch();
        }


    }
    return 0;
}
示例#21
0
//===================================================================
// Reads in the data from a file and inserts into BST and hashed
// array.
//===================================================================
void readInFile(DATA_HEAD *data) {
    FILE *dataFile;
    COMPANY *companyNode;
    char filename[MAX_CHARS], tmpName[MAX_CHARS];
    char ch;
    int tmpRev, tmpProfit, tmpNumEmployee;
    int i = 0, isDuplicate, len, size;

    do {
        printf("Please enter a filename [enter for default]:");
        fgets(filename, MAX_CHARS, stdin);

        if (filename[0] == '\n')
            strcpy(filename, default_file);
        else {
            //flush new line
            len = strlen(filename);

            if (filename[len - 1] == '\n' || filename[len - 1] == '\r')
                filename[len - 1] = '\0'; // change '\n' to '\0'
            else // no '\n' read, so flush to '\n'
                while ((ch = getchar()) != '\n' && ch != '\r');
        }

        dataFile = fopen(filename, "r");
    } while(!dataFile);

    //Creates structures
    data->pTree  = createBST(myStringCompare);
    data->pStack = createStack();

    size = getArrSize(dataFile);
    //need to reopen connection
    dataFile = fopen(filename, "r");

    data->arraySize = size;
    data->count = 0;
    data->pHash = (HASH *)malloc(sizeof(DATA_HEAD) *data->arraySize);

    //initialize hashed array
    for (i = 0; i < data->arraySize; i++) {
        data->pHash[i].status = 0;
        data->pHash[i].numOfCollisions = 0;
        data->pHash[i].numOfProbes = 0;
        data->pHash[i].hashData = NULL;
    }

    //Reads in, parses, mallocs, assigns
    while (fscanf(dataFile, " %[^,],%d,%d,%d[^\n]", tmpName, &tmpRev, &tmpProfit, &tmpNumEmployee) != EOF)
    {
        companyNode = (COMPANY *)malloc(sizeof(COMPANY));

        //Checks to see if allocated properly
        if (!companyNode)
            exit(1);

        companyNode->companyName = (char *)malloc(strlen(tmpName) + 1);

        //Checks to see if allocated properly
        if (!(companyNode->companyName))
            exit(1);

        strcpy(companyNode->companyName, tmpName);
        companyNode->numberOfEmployees = tmpNumEmployee;
        companyNode->revenuePerBillion = tmpRev;
        companyNode->profitPerMillion = tmpProfit;

        //Inserts company data (name, revenue, profit, employees) into the BST
        //If duplicate, print an error
        isDuplicate = searchHash(data, tmpName, companyNode);
        if (isDuplicate == 1)
            printf("ERROR: DUPLICATE DATA\n");
        else
        {
            insertHash(data, companyNode);
            insertBST(data->pTree, companyNode);
            data->count++;
        }
    }
    printf("\nNumber Of Data Records read in: %d\n\n", data->count);
    fclose(dataFile);
}
示例#22
0
void setup(){
	tree = createBST(compare);
}