(1)二叉树的建立
typedef struct BinaryTreeNode {
char value;
struct BinaryTreeNode *left;
struct BinaryTreeNode *right;
}BiTreeNode, *BiTree;
//二叉树的建立
void createBiTree(BiTree &root) {
char data;
cin >> data;
if(data == '#') {
root = NULL;
}
else {
root = new BiTreeNode();
root->value = data;
createBiTree(root->left);
createBiTree(root->right);
}
}
(2)二叉树的先序遍历
//先序遍历二叉树_递归
void preOrder_Recursively(BiTree &root) {
if(root != NULL) {
cout << root->value << " ";
preOrder_Recursively(root->left);
preOrder_Recursively(root->right);
}
}
//先序遍历二叉树_非递归
void preOrder_UnRecursively(BiTree &root) {
stack<BiTree> sta;
BiTree p = root; //p为遍历指针
while(p != NULL || !sta.empty()) {
if(p != NULL) {
sta.push(p);
cout << p->value << " ";
p = p->left;
}
else {
p = sta.top();
sta.pop();
p = p->right;
}
}
}
(3)二叉树的中序遍历
//中序遍历二叉树_递归
void inOrder_Recursively(BiTree &root) {
if(root != NULL) {
inOrder_Recursively(root->left);
cout << root->value << " ";
inOrder_Recursively(root->right);
}
}
//中序遍历二叉树_非递归
void inOrder_UnRecursively(BiTree &root) {
stack<BiTree> sta;
BiTree p = root; //p为遍历指针
while(p != NULL || !sta.empty()) {
if(p != NULL) {
sta.push(p);
p = p->left;
}
else {
p = sta.top();
sta.pop();
cout << p->value << " ";
p = p->right;
}
}
}
(4)二叉树的后序遍历
void postOrder_UnRecursively(BiTree &root) {
stack<BiTreePost> sta;
BiTree p = root;
BiTreePost post;
while(p != NULL || !sta.empty()) {
while(p != NULL) {
post = new BiTreeNodePost();
post->biTree = p;
post->tag = 'L';
sta.push(post);
p = p->left;
}
while(!sta.empty() && (sta.top())->tag == 'R') {
post = sta.top();
sta.pop();
cout << post->biTree->value << " ";
}
if(!sta.empty()) {
BiTreePost post = sta.top();
post->tag = 'R';
p = post->biTree->right;
}
}
}
(5)二叉树的层次遍历
//层次遍历
void levelOrder(BiTree &root) {
queue<BiTree> que;
BiTree p = root;
if(p != NULL)
que.push(p);
while(!que.empty()) {
p = que.front();
cout << p->value << " ";
que.pop();
if(p->left != NULL)
que.push(p->left);
if(p->right != NULL)
que.push(p->right);
}
}