From 78b3dda9017aab8c9031ce67eb30f29036e5df24 Mon Sep 17 00:00:00 2001 From: Shine wOng <1551885@tongji.edu.cn> Date: Sun, 9 Jun 2019 14:25:28 +0800 Subject: [PATCH] implement BinNode::succ(), with all tests passed. --- thu_dsa/chp5/binNode.h | 17 ++++++++++++++++- thu_dsa/chp5/testBinTree.cpp | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/thu_dsa/chp5/binNode.h b/thu_dsa/chp5/binNode.h index 9ba252a..002f7a9 100644 --- a/thu_dsa/chp5/binNode.h +++ b/thu_dsa/chp5/binNode.h @@ -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 void preOrder_Re(VST &visit); @@ -105,6 +106,20 @@ BinNodePosi(T) BinNode::insertAsRC(T const &val){ return currNode; } +template +BinNodePosi(T) BinNode::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 template diff --git a/thu_dsa/chp5/testBinTree.cpp b/thu_dsa/chp5/testBinTree.cpp index 5d5ca4c..22ccb60 100644 --- a/thu_dsa/chp5/testBinTree.cpp +++ b/thu_dsa/chp5/testBinTree.cpp @@ -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 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 struct Print{ virtual void operator()(T const &val){