Created
September 11, 2012 12:20
-
-
Save rod-dot-codes/3698010 to your computer and use it in GitHub Desktop.
Assignment 2 Question 6 Trees Traversal Code
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 <boost/scoped_ptr.hpp> | |
#include <iostream> | |
#include <queue> | |
template<typename T> | |
class TreeNode { | |
public: | |
TreeNode(const T& n, TreeNode* left = NULL, TreeNode* right = NULL) | |
: mValue(n), | |
mLeft(left), | |
mRight(right) {} | |
T getValue() const { | |
return mValue; | |
} | |
TreeNode* left() const { | |
return mLeft.get(); | |
} | |
TreeNode* right() const { | |
return mRight.get(); | |
} | |
void preorderTraverse() const { | |
std::cout << " " << getValue(); | |
if(mLeft) { mLeft->preorderTraverse(); } | |
if(mRight) { mRight->preorderTraverse(); } | |
} | |
void inorderTraverse() const { | |
if(mLeft) { mLeft->inorderTraverse(); } | |
std::cout << " " << getValue(); | |
if(mRight) { mRight->inorderTraverse(); } | |
} | |
void postorderTraverse() const { | |
if(mLeft) { mLeft->postorderTraverse(); } | |
if(mRight) { mRight->postorderTraverse(); } | |
std::cout << " " << getValue(); | |
} | |
void levelorderTraverse() const { | |
std::queue<const TreeNode*> q; | |
q.push(this); | |
while(!q.empty()) { | |
const TreeNode* n = q.front(); | |
q.pop(); | |
std::cout << " " << n->getValue(); | |
if(n->left()) { q.push(n->left()); } | |
if(n->right()) { q.push(n->right()); } | |
} | |
} | |
protected: | |
T mValue; | |
boost::scoped_ptr<TreeNode> mLeft; | |
boost::scoped_ptr<TreeNode> mRight; | |
private: | |
TreeNode(); | |
}; | |
int main() { | |
TreeNode<char> root('-', | |
new TreeNode<char>('*', | |
new TreeNode<char>('x'), | |
new TreeNode<char>('+', | |
new TreeNode<char>('y'),new TreeNode<char>('z')) | |
),//left | |
new TreeNode<char>('/', | |
new TreeNode<char>('-', | |
new TreeNode<char>('a'), | |
new TreeNode<char>('b')),new TreeNode<char>('c'))); | |
std::cout << "preorder: "; | |
root.preorderTraverse(); | |
std::cout << std::endl; | |
std::cout << "inorder: "; | |
root.inorderTraverse(); | |
std::cout << std::endl; | |
std::cout << "postorder: "; | |
root.postorderTraverse(); | |
std::cout << std::endl; | |
std::cout << "level-order:"; | |
root.levelorderTraverse(); | |
std::cout << std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment