Last active
August 29, 2015 14:05
-
-
Save barahilia/56ad134c0db5147351ab to your computer and use it in GitHub Desktop.
TDD for trees comparison in C++
This file contains 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
Build with: `g++ test.cpp && ./a.out` | |
For editing two files in `vim` run command `:vsplit tree.h`. | |
http://www.cs.swarthmore.edu/help/vim/windows.html |
This file contains 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 <string> | |
#include "tree.h" | |
using namespace std; | |
void assert(bool test, string message) { | |
string res = test ? " pass" : "failure"; | |
cout << res << " - " << message << endl; | |
} | |
int main() { | |
node n; | |
n.data = 42; n.left = 0; n.right = 0; | |
assert(n.data == 42, "node defines data"); | |
node * a = 0; node * b = 0; | |
assert( | |
compare(a, b), | |
"compares two null trees" | |
); | |
a = new node; | |
assert( | |
compare(a, b) == false, | |
"compares null and non-null trees" | |
); | |
b = new node; a->data = 42; b->data = 13; | |
assert( | |
compare(a, b) == false, | |
"compares non-null trees diff data" | |
); | |
b->data = 42; | |
a->left = 0; a->right = 0; | |
b->left = 0; b->right = 0; | |
assert( | |
compare(a, b) == true, | |
"compares non-null trees same data" | |
); | |
a->left = new node; | |
assert( | |
compare(a, b) == false, | |
"non-null trees same data diff subtree" | |
); | |
return 0; | |
} |
This file contains 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
// This file will define a tree data structure | |
// and a function that compares two trees | |
class node { | |
public: | |
int data; | |
node * left; | |
node * right; | |
}; | |
bool compare(node * a, node * b) { | |
if( a == 0 && b == 0 ) { | |
return true; | |
} | |
if( a == 0 || b == 0 ) { | |
return false; | |
} | |
if( a->data != b->data ) { | |
return false; | |
} | |
return compare(a->left, b->left) && | |
compare(a->right, b->right); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment