summaryrefslogtreecommitdiff
path: root/tree.cpp
blob: 690c9643a8c663a596fcefb423a60dd7cd4a6c88 (plain)
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126

#include <cstdlib>
#include <iostream>
#include <string>
#include <cassert>

using namespace std;

struct node
{
    node* left;
    node* right;
    long value;

    node(long _value) : left(NULL), right(NULL), value(_value) {}
};

void clean_node(node* nd)
{
    if (!nd)
        return;

    clean_node(nd->left);
    nd->left = NULL;
    clean_node(nd->right);
    nd->right = NULL;
    delete nd;
}

void clean_tree(node* root)
{
    clean_node(root);
}

void print_node(node* nd)
{
    if (!nd)
        return;

    print_node(nd->left);
    cout <<  nd->value << " ";
    print_node(nd->right);
}

void print_tree(node* root)
{
    cout << "tree content: ";
    print_node(root);
    cout << endl;
}

void insert_value(node* root, long value)
{
    while (true)
    {
        assert(root);
        if (root->value == value)
            // duplicates are not allowed.
            return;

        if (value < root->value)
        {
            if (!root->left)
            {
                root->left = new node(value);
                return;
            }

            root = root->left;
        }
        else
        {
            assert(value > root->value);
            if (!root->right)
            {
                root->right = new node(value);
                return;
            }

            root = root->right;
        }
    }
}

int main()
{
    node* root = NULL;
    while (true)
    {
        string val;
        cin >> val;

        if (val.empty())
            break;

        if (val == "q" || val == "quit")
        {
            cout << "terminating" << endl;
            break;
        }

        // End position on successful conversion.
        const char* end_pos = val.c_str() + val.size();

        char* end_ptr = NULL;
        long lval = strtol(&val[0], &end_ptr, 10);
        if (end_pos != end_ptr)
        {
            // String didn't get scanned in its entirety. Must have failed.
            cerr << "invalid integer: " << val << endl;
            continue;
        }
        cout << "input number: " << lval << endl;

        if (!root)
            root = new node(lval);
        else
            insert_value(root, lval);

        print_tree(root);
    }

    clean_tree(root);

    return EXIT_SUCCESS;
}