二叉樹——C++實現
阿新 • • 發佈:2019-02-09
#include<iostream>
#include<queue>
using namespace std;
template<class T> class BinaryTree;
template<class T>
class TreeNode
{
public:
TreeNode()
{
leftChild = NULL;
rightChild = NULL;
}
T data;
TreeNode<T> *leftChild;
TreeNode<T> *rightChild;
};
template<class T>
class BinaryTree
{
public:
void LevelOrder();
void Visit(TreeNode<T>* currentNode);
public:
TreeNode<T> *root;
};
template<class T>
void BinaryTree<T>::Visit(TreeNode<T>* currentNode)
{
std::cout<<currentNode->data<<endl;
}
template<class T>
void BinaryTree<T>::LevelOrder()
{
std::queue<TreeNode<T>*> q;
TreeNode<T>* currentNode = root;
while(currentNode)
{
Visit(currentNode);
if(currentNode->leftChild) q.push(currentNode->leftChild);
if(currentNode->rightChild) q.push(currentNode->rightChild);
if(q.empty()) return;
currentNode = q.front();
q.pop();
}
}
int main()
{
BinaryTree<char> tree;
TreeNode<char> plus,decrese,mul,divide,a,b,c,d,e;
plus.data = '+';
decrese.data = '-';
mul.data = '*';
divide.data = '/';
a.data = 'A';
b.data = 'B';
c.data = 'C';
d.data = 'D';
e.data = 'E';
tree.root = +
plus.leftChild = &decrese;
plus.rightChild = &e;
decrese.leftChild = &mul;
decrese.rightChild = &d;
mul.leftChild = ÷
mul.rightChild = &c;
divide.leftChild = &a;
divide.rightChild = &b;
tree.LevelOrder();
return 0;
}
#include<queue>
using namespace std;
template<class T> class BinaryTree;
template<class T>
class TreeNode
{
public:
TreeNode()
{
leftChild = NULL;
rightChild = NULL;
}
T data;
TreeNode<T> *leftChild;
TreeNode<T> *rightChild;
};
template<class T>
class BinaryTree
{
public:
void LevelOrder();
void Visit(TreeNode<T>* currentNode);
public:
TreeNode<T> *root;
};
template<class T>
void BinaryTree<T>::Visit(TreeNode<T>* currentNode)
{
std::cout<<currentNode->data<<endl;
}
template<class T>
void BinaryTree<T>::LevelOrder()
{
std::queue<TreeNode<T>*> q;
TreeNode<T>* currentNode = root;
while(currentNode)
{
Visit(currentNode);
if(currentNode->leftChild) q.push(currentNode->leftChild);
if(currentNode->rightChild) q.push(currentNode->rightChild);
if(q.empty()) return;
currentNode = q.front();
q.pop();
}
}
int main()
{
BinaryTree<char> tree;
TreeNode<char> plus,decrese,mul,divide,a,b,c,d,e;
plus.data = '+';
decrese.data = '-';
mul.data = '*';
divide.data = '/';
a.data = 'A';
b.data = 'B';
c.data = 'C';
d.data = 'D';
e.data = 'E';
tree.root = +
plus.leftChild = &decrese;
plus.rightChild = &e;
decrese.leftChild = &mul;
decrese.rightChild = &d;
mul.leftChild = ÷
mul.rightChild = &c;
divide.leftChild = &a;
divide.rightChild = &b;
tree.LevelOrder();
return 0;
}