#include <iostream>
#include <queue>
#include <stack>
using namespace std;
template <class T>
struct BinaryTreeNode
{
T data;
BinaryTreeNode<T> *left;
BinaryTreeNode<T> *right;
BinaryTreeNode(T x) : data(x), left(nullptr), right(nullptr) {}
};
template <class T>
class BinaryTree
{
private:
BinaryTreeNode<T> *root;
public:
BinaryTree() {}
BinaryTree(BinaryTreeNode<T>* node):root(node) {}
void deleteBinaryTree(BinaryTreeNode<T>* node)
{
if(node!=nullptr)
{
deleteBinaryTree(node->left);
deleteBinaryTree(node->right);
}
delete node;
}
~BinaryTree() { deleteBinaryTree(root); }
bool isEmpty() { return root == nullptr; }
void visit(BinaryTreeNode<T>* t)
{
if(t!=nullptr)
cout << t->data << endl;
}
//层次遍历
/*
1.根节点入队
2.while(队不空)
3.出队
4.拜访出队元素
5.出队元素左右孩子节点依次入队
*/
void LevelOrder(BinaryTreeNode<T>* root)
{
if(root==nullptr)
return;
queue<BinaryTreeNode<T>*> q;
q.push(root);
while(!q.empty())
{
BinaryTreeNode<T> *node;
node = q.front();
q.pop();
visit(node);
if (node->left != nullptr)
q.push(node->left);
if (node->right != nullptr)
q.push(node->right);
}
}
// 前序遍历
void PreOrder(BinaryTreeNode<T> *root)
{
if (root != nullptr)
{
visit(root);
PreOrder(root->left);
PreOrder(root->right);
}
}
// 中序遍历
void InOrder(BinaryTreeNode<T> *root)
{
if (root != nullptr)
{
InOrder(root->left);
visit(root);
InOrder(root->right);
}
}
// 前序遍历
void PostOrder(BinaryTreeNode<T> *root)
{
if (root != nullptr)
{
PostOrder(root->left);
PostOrder(root->right);
visit(root);
}
}
BinaryTreeNode<T> *PreInBuildTree(string pre,string in)
{
if(pre.empty())
return nullptr;
BinaryTreeNode<T> *root = new BinaryTreeNode<T>(pre[0]);
int pos = in.find(pre[0]);
root->left = PreInBuildTree(pre.substr(1, pos), in.substr(0, pos));
root->right = PreInBuildTree(pre.substr(pos+1), in.substr(pos+1));
return root;
}
BinaryTreeNode<T> *PostInBuildTree(string post, string in)
{
if (post.empty())
return nullptr;
BinaryTreeNode<T> *root = new BinaryTreeNode<T>(post.back());
int pos = in.find(post.back());
post.pop_back();
root->left = PostInBuildTree(post.substr(0,pos), in.substr(0, pos));
root->right = PostInBuildTree(post.substr(pos), in.substr(pos + 1));
return root;
}
void setRoot(BinaryTreeNode<T> *t) { root = t;}
BinaryTreeNode<T> *getRoot() { return root; }
};
int main()
{
string in = "42513";
string pre = "12453";
string post = "45231";
BinaryTree<char> Bt;
Bt.setRoot(Bt.PreInBuildTree(pre, in));
Bt.LevelOrder(Bt.getRoot());
cout << endl;
Bt.setRoot(Bt.PostInBuildTree(post, in));
Bt.LevelOrder(Bt.getRoot());
cout << endl;
Bt.setRoot(Bt.PostInBuildTree("", ""));
Bt.LevelOrder(Bt.getRoot());
return 0;
}

被折叠的 条评论
为什么被折叠?



