implement BinNode<T>::succ(), with all tests passed.

This commit is contained in:
Shine wOng
2019-06-09 14:25:28 +08:00
parent 30b5090612
commit 78b3dda901
2 changed files with 37 additions and 1 deletions

View File

@@ -26,11 +26,12 @@ public:
//constructor
BinNode() : parent(nullptr), leftChild(nullptr), rightChild(nullptr), height(0), color(0), npl(0) {};
BinNode(T const &val) : parent(nullptr), leftChild(nullptr), rightChild(nullptr), data(val), height(0), color(0), npl(0) {};
BinNode(T const &val, BinNodePosi(T) p): parent(p), leftChild(nullptr), rightChild(nullptr), data(val), height(0), color(0), npl(0) {};
int size() const; //compute the size of the tree rooted at current node
BinNodePosi(T) insertAsLC(T const &val); //always assume that this.leftChild == nullptr
BinNodePosi(T) insertAsRC(T const &val); //always assume that this.rightChild == nullptr
BinNodePosi(T) succ() const; //return the direct successor of current node
BinNodePosi(T) succ(); //return the direct successor of current node
//tree traversal
template <typename VST> void preOrder_Re(VST &visit);
@@ -105,6 +106,20 @@ BinNodePosi(T) BinNode<T>::insertAsRC(T const &val){
return currNode;
}
template <typename T>
BinNodePosi(T) BinNode<T>::succ(){
BinNodePosi(T) succ;
if(rightChild){
succ = rightChild;
while (succ->leftChild) succ = succ->leftChild;
}else{
succ = this;
while(succ->parent && succ == succ->parent->rightChild) succ = succ->parent;
succ = succ->parent;
}
return succ;
}
//tree traversal
template <typename T> template <typename VST>

View File

@@ -7,6 +7,7 @@ using std::endl;
void test_insert();
void test_size();
void test_succ();
void test_preTraversal();
void test_inTraversal();
void test_postTraversal();
@@ -17,6 +18,7 @@ int main(){
test_insert();
test_size();
test_succ();
test_preTraversal();
test_inTraversal();
test_postTraversal();
@@ -68,6 +70,25 @@ void test_size(){
assert(root->size() == 3);
}
void test_succ(){
//construct a binary tree
BinTree<int> intTree;
BinNodePosi(int) root = intTree.insertAsRoot(8);
BinNodePosi(int) left = intTree.insertAsLC(root, 7);
BinNodePosi(int) right = intTree.insertAsRC(root, 14);
BinNodePosi(int) first = intTree.insertAsLC(left, 4);
intTree.insertAsRC(left, 3);
intTree.insertAsLC(right, 12);
intTree.insertAsRC(right, 18);
//test succ
int inOrder[] = { 4, 7, 3, 8, 12, 14, 18 };
BinNodePosi(int) x = first;
for (int ix = 0; x; ++ix, x = x->succ()) {
assert(x->data == inOrder[ix]);
}
}
template <typename T>
struct Print{
virtual void operator()(T const &val){