Algebraic data types: Difference between revisions

Content added Content deleted
Line 712: Line 712:
| black(ColoredTree left, ColoredTree right);
| black(ColoredTree left, ColoredTree right);
// Count the number of red nodes
// Count the number of black nodes
public int cntRed(ColoredTree t){
public int cntBlack(ColoredTree t){
int c = 0;
int c = 0;
visit(t) {
visit(t) {
case red(_,_): c = c + 1;
case black(_,_): c += 1;
};
};
return c;
return c;
}
}


// Returns if a tree is balanced
public bool balance(ColoredTree t){
visit(t){
case black(a,b): if (cntBlack(a) == cntBlack(b)) true; else return false;
case red(a,b): if (cntBlack(a) == cntBlack(b)) true; else return false;
}
return true;
}
// Compute the sum of all integer leaves
// Compute the sum of all integer leaves
public int addLeaves(ColoredTree t){
public int addLeaves(ColoredTree t){
int c = 0;
int c = 0;
visit(t) {
visit(t) {
case leaf(int N): c = c + N;
case leaf(int N): c += N;
};
};
return c;
return c;