Created
August 12, 2011 12:58
-
-
Save yasith/1141976 to your computer and use it in GitHub Desktop.
Binary tree implementation in C++
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <cmath> | |
#define p(x) cout << #x << ":" << x << endl; | |
#define LIMIT (int)pow(2, 3) | |
using namespace std; | |
class Node{ | |
public: | |
int t; //total | |
int s, e; //start, end | |
Node *l; | |
Node *r; | |
void init(int _t, int _s, int _e){ | |
t = _t; | |
s = _s; | |
e = _e; | |
l = NULL; | |
r = NULL; | |
} | |
} tree; | |
int add(Node *n, int s, int e){ | |
if(s > e) return 0; | |
//p(n->s) p(n->e) | |
int size = (n->e - n->s)+1; | |
if(s == n->s && e == n->e){ | |
n->t = size; | |
}else{ | |
if(n->l == NULL){ | |
Node *nl = new Node; | |
nl->init(0, n->s, n->s+(size/2)-1); | |
n->l = nl; | |
} | |
if(n->r == NULL){ | |
Node *nr = new Node; | |
nr->init(0, n->s+(size/2), n->e); | |
n->r = nr; | |
} | |
n->t = add(n->l, s, min(n->l->e, e)) + add(n->r, max(n->r->s, s), e); | |
} | |
return n->t; | |
} | |
int remove(Node *n, int s, int e){ | |
if(s > e) return n->t; | |
//p(n->s) p(n->e) | |
int size = (n->e - n->s)+1; | |
if(s == n->s && e == n->e){ | |
n->t = 0; | |
}else{ | |
int total = 0; | |
if(n->t == size){ | |
Node *nl = new Node; | |
nl->init(size/2, n->s, n->s+(size/2)-1); | |
n->l = nl; | |
Node *nr = new Node; | |
nr->init(size/2, n->s+(size/2), n->e); | |
n->r = nr; | |
} | |
if(n->l != NULL){ | |
total += remove(n->l, s, min(n->l->e, e)); | |
} | |
if(n->r != NULL){ | |
total += remove(n->r, max(n->r->s, s), e); | |
} | |
//p(n->t) | |
n->t = total; | |
} | |
return n->t; | |
} | |
int getCount(){ | |
return tree.t; | |
} | |
int main(){ | |
tree.init(0, 1, LIMIT); | |
//p(tree.t) p(tree.s) p(tree.e) | |
cout << add(&tree, 3, 8) << endl; | |
cout << remove(&tree, 4, 5) << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment