summaryrefslogtreecommitdiff
path: root/Build/source/utils/asymptote/base/tree.asy
blob: 0f3559112c3f335b8561dd725d803c8fcf47f6fa (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
/*****
 * treedef.asy
 * Andy Hammerlindl 2003/10/25
 *
 * Implements a dynamic binary search tree.
 *****/

struct tree
{
  tree left = null;
  tree right = null;
  int key = 0;
  int value = 0;
}

tree newtree()
{
  return null;
}

tree add(tree t, int key, int value)
{
  if (t == null) {
    tree tt;
    tt.key = key; tt.value = value;
    return tt;
  }
  else if (key == t.key) {
    return t;
  }
  else if (key < t.key) {
    tree tt;
    tt.left = add(t.left, key, value);
    tt.key = t.key;
    tt.value = t.value;
    tt.right = t.right;
    return tt;
  }
  else {
    tree tt;
    tt.left = t.left;
    tt.key = t.key;
    tt.value = t.value;
    tt.right = add(t.right, key, value);
    return tt;
  }
}

bool contains(tree t, int key)
{
  if (t == null)
    return false;
  else if (key == t.key)
    return true;
  else if (key < t.key)
    return contains(t.left, key);
  else
    return contains(t.right, key);
}

int lookup(tree t, int key)
{
  if (t == null)
    return 0;
  else if (key == t.key)
    return t.value;
  else if (key < t.key)
    return lookup(t.left, key);
  else
    return lookup(t.right, key);
}

void write(file out=stdout, tree t)
{
  if (t != null) {
    if(t.left != null) {
      write(out,t.left);
    }
    write(out,t.key);
    write(out,"->");
    write(out,t.value,endl);
    if (t.right != null) {
      write(out,t.right);
    }
  }
}