Next Spaceship

Driving into future…

Binary-Search Tree Template

| Comments

This is a Binary-Search Tree template written by Leon.

Binary Search Tree
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
#include <iostream>
#include <cstdio>
#include <cstring>
//Binary Search Tree
//Created by Leon
//Oct 19, 2009
using namespace std;

struct tree {
    int key;
    int value;
    tree *l, *r;
};

tree* Insert(tree* t, int c) {
    tree *nt = new tree();
    nt->l = 0, nt->r = 0, nt->value = 1;
    nt->key = c;
    if (t == 0) {
        return nt;
    }
    tree *tmp = t;
    tree *p;
    while (tmp != 0 && tmp->key != c) {
        p = tmp;
        if (tmp->key < c) {
            tmp = tmp->r;
        }
        else {
            tmp = tmp->l;
        }
    }
    if (tmp == 0) {
        tmp = nt;
        if (p->key < c) {
            p->r = tmp;
        }
        else {
            p->l = tmp;
        }
    }
    else {
        tmp->value++;
    }
    return t;
}

void InOrder(tree* t) {
    if (t != 0) {
        InOrder(t->l);
        printf("%d %dn", t->key, t->value);
        InOrder(t->r);
    }
}

int main() {
    tree* root = 0;
    root = Insert(root, 3);
    root = Insert(root, 19);
    root = Insert(root, 2);
    root = Insert(root, 5);
    root = Insert(root, 2);
    InOrder(root);
    return 0;
}

Comments