summaryrefslogtreecommitdiff
path: root/algorithms/binary_tree.cc
blob: d912aecc42ceb072132e57e352b2c6134d1f8a9e (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
#include <iostream>

using std::cout;
using std::endl;


struct Node {
  int value;
  Node* pLeft;
  Node* pRight;
};

struct Tree {
  Node* pRoot;
};

Node*
new_node(int value)
{
  Node* node = new Node;
  node->value = value;
  node->pLeft = node->pRight = NULL;
  return node;
}

void
delete_node(Node* pNode)
{
  if(pNode->pLeft)
    delete pNode->pLeft;
  if(pNode->pRight)
    delete pNode->pRight;
  delete pNode;
}

void
insert_node(Node* n, Node* i)
{
  if(i->value <= n->value) {
    if(n->pLeft) {
      insert_node(n->pLeft, i);
    } else {
      n->pLeft = i;
    }
  } else {
    if(n->pRight) {
      insert_node(n->pRight, i);
    } else {
      n->pRight = i;
    }
  }
}

void
insert(Tree& tree, int value)
{
  Node *n = new_node(value);

  if(!tree.pRoot) {
    tree.pRoot = n;
  } else {
    if(n->value <= tree.pRoot->value) {
      if(tree.pRoot->pLeft) {
        insert_node(tree.pRoot->pLeft, n);
      } else {
        tree.pRoot->pLeft = n;
      }
    } else {
      if(tree.pRoot->pRight) {
        insert_node(tree.pRoot->pRight, n);
      } else {
        tree.pRoot->pRight = n;
      }
    }
  }
}

void
print_nodes_inorder(Node *n)
{
  if(n->pLeft) {
    print_nodes_inorder(n->pLeft);
  }

  cout << n->value << endl;

  if(n->pRight) {
    print_nodes_inorder(n->pRight);
  }
}

void
print_sorted(Tree& tree)
{
  Node *n=tree.pRoot;

  print_nodes_inorder(n);
}

int
main()
{
  Tree tree;
  tree.pRoot = NULL;

  int feld[10] = {8, 12, 5, 24, 2, 6, 98, 67, 1, 6};

  for(int i = 0; i < 10; ++i)
    insert(tree, feld[i]);

  print_sorted(tree);

  if(tree.pRoot)
    delete_node(tree.pRoot);

  return 0;
}