文章目录提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
- 正文
- 示例代码:
- 执行结果:
正文
递归先序、中序、后序遍历二叉树的代码大家应该知道,这里只举例说明递归先序遍历的代码:
void preOrder(Tree *root) {
visit(root); //按照需要修改,此处是对结点进行操作的代码
preOrder(root->left);
preOrder(root->right);
}
完全二叉树的序列化特性如下:
因此,上述的代码可以变为:
int tree[N + 1] //二叉树的序列化数组,下标0不存储数据,用[1,N+1]的空间
void preOrder(int index) {
if (index > N) return; //如果访问的结点编号大于总结点数,则返回上一层
visit(tree[index]); //按照需要修改,此处是对结点进行操作的代码
preOrder(index * 2); //访问左结点
preOrder(index * 2 + 1); // 访问右结点
}
此段代码中index表示先序遍历过程中,本次要访问的结点编号,而层次遍历则是顺序遍历二叉树的序列化数组,且因为完全二叉树,所以在遍历过程中不会遇到空结点。中序和后序的做法类似,只是visit()调用的地方不同。
那么反过来,通过先序遍历序列怎么得到二叉树的序列化数组呢?
int i = 0;
pre[N-1] = {......};
void buildTreeByPre(int index) {
if (index > N) return;
tree[index] = pre[i++]; //按照先序序列的index跳转方式,将先序序列顺序放入对应tree的index下标中。比如先序序列第一个结点根节点(编号1),然后左子树根节点(编号:2*1=2),以此类推
buildTreeByPre(index * 2);
buildTreeByPre(index * 2 + 1);
}
上述代码实现了在先序遍历的过程中将先序序列顺序放到tree数组的对应index位置上。index的跳转方式按照完全二叉树的特性和先序遍历的规则。
示例代码:该代码所用完全二叉树为:
#include执行结果:#include #define MAXSIZE 8 //由完全二叉树的先、中、后序序列分别构造完全二叉树,将二叉树序列化用顺序表存储,该顺序表存放顺序即为层次遍历顺序 using namespace std; int pre[MAXSIZE] = {7, 3, 6, 8, 1, 2, 5, 4}; //先序序列 int in[MAXSIZE] = {8, 6, 3, 1, 7 ,5, 4, 2}; //中序序列 int post[MAXSIZE] = {8, 6, 1, 3, 5, 4, 2, 7}; //后序序列 int level1[MAXSIZE + 1]; // 下标0不使用,空着。 int level2[MAXSIZE + 1]; int level3[MAXSIZE + 1]; int i1 = 0; //用于在递归中遍历先序序列数组 int i2 = 0; int i3 = 0; void buildTreeByPre(int index) { if (index > MAXSIZE) return; level1[index] = pre[i1++]; buildTreeByPre(index * 2); buildTreeByPre(index * 2 + 1); } void buildTreeByIn(int index) { if (index > MAXSIZE) return; buildTreeByIn(index * 2); level2[index] = in[i2++]; buildTreeByIn(index * 2 + 1); } void buildTreeByPost(int index) { if (index > MAXSIZE) return; buildTreeByPost(index * 2); buildTreeByPost(index * 2 + 1); level3[index] = post[i3++]; } void print(string description, int level[MAXSIZE + 1]) { cout< cout< buildTreeByPre(1); buildTreeByIn(1); buildTreeByPost(1); print("由先序序列得到的完全二叉树序列数组(层次遍历序列):", level1); print("由中序序列得到的完全二叉树序列数组(层次遍历序列):", level2); print("由后序序列得到的完全二叉树序列数组(层次遍历序列):", level3); return 0; }



