From fd26fbb5507f8fe555ff06e958b5885a7edf6206 Mon Sep 17 00:00:00 2001 From: Shine wOng <1551885@tongji.edu.cn> Date: Mon, 27 May 2019 16:52:16 +0800 Subject: [PATCH] add iterative post-traversal algorithm, tests passed. --- thu_dsa/chp5/binNode.h | 26 ++++++++++++++++++++++++++ thu_dsa/chp5/testBinTree.cpp | 2 ++ 2 files changed, 28 insertions(+) diff --git a/thu_dsa/chp5/binNode.h b/thu_dsa/chp5/binNode.h index 9e02c22..35d7308 100644 --- a/thu_dsa/chp5/binNode.h +++ b/thu_dsa/chp5/binNode.h @@ -12,6 +12,7 @@ protected: template void visitAlongLeftBranch(VST &visit, Stack &S); void goAlongLeftBranch(Stack &S); + void goToHLVFL(Stack &S); //Highest Leaf Visible From Left public: BinNodePosi(T) parent; @@ -63,6 +64,19 @@ void BinNode::goAlongLeftBranch(Stack &S){ } } +template +void BinNode::goToHLVFL(Stack &S){ + BinNodePosi(T) curr; + while(curr = S.top()){ + if(curr->leftChild){ + if (curr->rightChild) S.push(curr->rightChild); + S.push(curr->leftChild); + } + else S.push(curr->rightChild); + } + S.pop(); +} + //public interfaces template @@ -151,6 +165,18 @@ void BinNode::postOrder_Re(VST &visit){ visit(this->data); } +template template +void BinNode::postOrder_It(VST &visit){ + Stack S; + BinNodePosi(T) curr = this; + S.push(curr); + while(!S.empty()){ + if(S.top() != curr->parent) goToHLVFL(S); + curr = S.pop(); + visit(curr->data); + } +} + template template void BinNode::levelOrder(VST &visit){ Queue q; diff --git a/thu_dsa/chp5/testBinTree.cpp b/thu_dsa/chp5/testBinTree.cpp index 3d50704..0af7703 100644 --- a/thu_dsa/chp5/testBinTree.cpp +++ b/thu_dsa/chp5/testBinTree.cpp @@ -130,6 +130,8 @@ void test_postTraversal(){ root->postOrder_Re(Print()); cout << endl; + root->postOrder_It(Print()); + cout << endl; } void test_levelTraversal(){