Может ли кто-нибудь показать мне, как написать двоичное дерево поиска с 31 различными словами? С++
I have tried but it does not print out in order, I was wondering if there was anyone who was willing to help.
Что я уже пробовал:
#include<iostream> #include<string.h> #include<cstdlib> using namespace std; struct bst { string data; struct bst *left, *right; }; struct bst *newNode(string key) { struct bst *temp = new struct bst (); temp -> data = key; temp -> left = temp -> right = NULL; return temp; } struct bst * insertNode(struct bst * stem, string key) { if (stem == NULL) return newNode(key); if (key < stem -> data) stem -> left = insertNode(stem -> left, key); else stem->right = insertNode(stem -> right, key); return stem; } void printBT(string prefix, bst * stem, int isLeft) { if(stem != NULL ) { cout << stem -> data << endl; printBT(prefix + (isLeft ? "| " : " "), stem -> left, 1); printBT(prefix + (isLeft ? "| " : " "), stem -> right, 0); } } void insert(bst *& stem, string values[], int start, int end) { if(start<=end){ int mid = (end+start)/2; stem = insertNode(stem,values[mid]); insert(stem,values,start,mid-1); insert(stem,values,mid+1,end); } } int main() { string list[] = {"after","also", "any", "back", "because", "come", "day", "even", "first", "give", "how", "its", "look", "most", "new", "now", "only", "other", "our", "over", "than", "then", "these", "think", "two", "us", "use", "want", "way", "well", "work"}; struct bst *stem = NULL; int length = sizeof(list)/sizeof(list[0]); insert(stem,list,0,length-1); printBT("", stem, 0); }
Rick York
Я рекомендую вам прочитать об использовании ключевого слова const. Большая часть ваших данных постоянна и должна быть помечена как const.