1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <iostream> using namespace std; class BST { int data; BST *left, *right; public:
BST();
BST(int);
BST* Insert(BST*, int);
void Inorder(BST*); };
BST ::BST() : data(0) , left(NULL) , right(NULL) { }
BST ::BST(int value) { data = value; left = right = NULL; }
BST* BST ::Insert(BST* root, int value) { if (!root) { return new BST(value); }
if (value > root->data) { root->right = Insert(root->right, value); } else { root->left = Insert(root->left, value); }
return root; }
void BST ::Inorder(BST* root) { if (!root) { return; } Inorder(root->left); cout << root->data << endl; Inorder(root->right); }
int main() { BST b, *root = NULL; root = b.Insert(root, 50); b.Insert(root, 30); b.Insert(root, 20); b.Insert(root, 40); b.Insert(root, 70); b.Insert(root, 60); b.Insert(root, 80);
b.Inorder(root); return 0; }
|