可以说数据结构里最重要的就是二叉树了,一点也不敢马虎,只能仔仔细细的看一遍课件,争取在讲图之前,把二叉树的openjudge做完,看完课件,做完书,还有实现一边树里的全部代码。
链式二叉树的创建
使用的是前序遍历创建的方法,使用#号标记空指针
代码:
BiNode<T>* Creat()
{
BiNode<T>* root;
char ch;
cin >> ch;
if (ch == '#')
root = NULL;
else
{
root = new BiNode<T>;
root->data = ch;
root->lchild = Creat();
root->rchild = Creat();
}
return root;
}
直接上全部的代码,下一篇整理非递归方法的前序中序后序遍历。
#include<iostream>
#include<stack>
#include<queue>
using namespace std;
template<class T>
struct BiNode
{
T data;
BiNode<T>* lchild, * rchild;
};
template <class T>
class BiTree
{
public:
BiTree() { root = Creat(); }
~BiTree() {}
void PreOrder() { PreOrder(root); }
void InOrder() { InOrder(root); }
void PostOrder() { PostOrder(root); }
void LevelOrder() { LevelOrder(root); }
private:
BiNode<T>* root;
BiNode<T>* Creat()
{
BiNode<T>* root;
char ch;
cin >> ch;
if (ch == '#')
root = NULL;
else
{
root = new BiNode<T>;
root->data = ch;
root->lchild = Creat();
root->rchild = Creat();
}
return root;
}
void PreOrder(BiNode<T>* root)
{
if (root == NULL)
return;
else
{
cout << root->data;
PreOrder(root->lchild);
PreOrder(root->rchild);
}
}
void InOrder(BiNode<T>* root)
{
if (root == NULL)
return;
else
{
InOrder(root->lchild);
cout << root->data;
InOrder(root->rchild);
}
}
void PostOrder(BiNode<T>* root)
{
if (root == NULL)
return;
else
{
PostOrder(root->lchild);
PostOrder(root->rchild);
cout << root->data;
}
}
void LevelOrder(BiNode<T>* root)
{
queue<BiNode<T>*>q;
if (root != NULL)
{
q.push(root);
}
while (!q.empty())
{
root = q.front();
q.pop();
cout << root->data;
if (root->lchild != NULL)
{
q.push(root->lchild);
}
if (root->rchild != NULL)
{
q.push(root->rchild);
}
}
cout << endl;
}
};
int main()
{
BiTree<char>bt;
cout << "层序遍历: ";
bt.LevelOrder();
cout << "前序遍历: ";
bt.PreOrder();
cout << endl;
cout << "中序遍历: ";
bt.InOrder();
cout << endl;
cout << "后序遍历: ";
bt.PostOrder();
cout << endl;
return 0;
}
顺序存储二叉树的创建
同样使用非常简单的递归算法。
#include<iostream>
using namespace std;
struct BiNode
{
int number;
char value;
}node[1000];
int N = 10;
void PreOrder(int num)
{
cout << node[num].value;
if (num * 2 <= N)
{
PreOrder(2 * num);
}
if (num * 2 + 1 <= N)
{
PreOrder(2 * num + 1);
}
}
void InOrder(int num)
{
if (num * 2 <= N)
{
InOrder(2 * num);
}
cout << node[num].value;
if (num * 2 + 1 <= N)
{
InOrder(2 * num + 1);
}
}
void PostOrder(int num)
{
if (num * 2 <= N)
{
PostOrder(2 * num);
}
if (num * 2 + 1 <= N)
{
PostOrder(2 * num + 1);
}
cout << node[num].value;
}
int main()
{
for (int i = 1; i <= N; ++i)
{
node[i].number = i;
node[i].value = 'A' + i - 1;
}
PreOrder(1);
cout << endl;
InOrder(1);
cout << endl;
PostOrder(1);
cout << endl;
return 0;
}