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
| #include <iostream> using namespace std;
struct Node { int data; struct Node* left; struct Node* right; };
void inorder(Node* root) { if (root != NULL) { inorder(root->left); cout << root->data << " "; inorder(root->right); } }
Node* add_node(Node* new_node, int n) { if (new_node == NULL) { new_node = new Node; new_node->data = n; new_node->left = NULL; new_node->right = NULL; return new_node; } return new_node; }
Node* input_data(Node* btree, int n) { if (btree == NULL) { btree = add_node(btree, n); }
if (n < btree->data) { btree->left = input_data(btree->left, n); } else if (n > btree->data) { btree->right = input_data(btree->right, n); }
return btree; }
int main() { Node* binary_tree = NULL; int n; while (cin >> n) { if (n == -1) break; binary_tree = input_data(binary_tree, n); } inorder(binary_tree); return 0; }
|