二叉树的建立与三种遍历
案例:
案例输入:ABD##EH###CF#IJ###G##
案例输出:
前序遍历:ABDEHCFIJG
中序遍历:DBHEAFJICG
后序遍历:DHDBJIFGCA
附:特别注意,用#表示空指针,叶节点处的两个空指针不能遗忘
运行结果
源代码如下:
#include<iostream>
#include<string>
using namespace std;
class Node {
public:
char data;
Node* left, * right;
Node(char d, Node* l = NULL, Node* r = NULL) :data(d), left(l), right(r) {}
Node() :left(NULL), right(NULL) {}
};
class BinaryTree {
public:
BinaryTree(Node* r = NULL) :root(r) {}
~BinaryTree() { delete root; }
Node*& Root() { return root; }
void createtree(Node*&);
void pretree(Node*);
void intree(Node*);
void posttree(Node*);
private:
Node* root;
};
//以先根遍历的方式建立二叉树
void BinaryTree::createtree(Node*& r) {
char temp;
cin >> temp;
if (temp == '#') { r = NULL; return; } //eg:ABD##EH###CF#IJ###G##
r = new Node(temp);
createtree(r->left);
createtree(r->right);
}
void BinaryTree::pretree(Node* root) {
if (root == NULL) return;
cout << root->data << '\t';
pretree(root->left);
pretree(root->right);
}
void BinaryTree::intree(Node* root) {
if (root == NULL) return;
intree(root->left);
cout << root->data << '\t';
intree(root->right);
}
void BinaryTree::posttree(Node* root) {
if (root == NULL) return;
posttree(root->left);
posttree(root->right);
cout << root->data << '\t';
}
int main() {
BinaryTree tree;
cout<<"请输入二叉树,#表示空指针"<<endl;
tree.createtree(tree.Root()); //案例输入:ABD##EH###CF#IJ###G##
cout<<"前序遍历结果如下:"<<endl;
tree.pretree(tree.Root()); //前序遍历
cout << endl;
cout<<"中序遍历结果如下:"<<endl;
tree.intree(tree.Root()); //中序遍历
cout << endl;
cout<<"后序遍历结果如下:"<<endl;
tree.posttree(tree.Root()); //后序遍历
cout << endl;
return 0;
}