C++二叉树线索化并遍历的示例代码
2015-03-21 14:14
465 查看
线索化的意义:二叉树的一般遍历方式都是递归的方式,而递归使用栈,当递归深度比较大时,很耗资源。线索化就是通过一次递归遍历,建立结点的前驱和后继关系。然后以后遍历的时候按这种关系遍历,就不用递归了。下面给出自己写的可运行代码。
#pragma once #include <iostream> #include <ostream> #include <cstdlib> using namespace std; struct Node { int i; Node* left, *right; bool leftThread, rightThread; // true则为线索,否则为普通的连线 }; class BinaryTree { private: // root是树的根结点,head是线索二叉树的头结点,pre在线索化的时候用到 Node *root, *head, *pre; // 按前序遍历建立二叉树 void createTree(Node*& n, int*& a1) { static int *a = a1; if (*a == -1) { n = NULL; } else { n = (Node*) malloc(sizeof (Node)); n->i = *a; n->leftThread = false; n->rightThread = false; createTree(n->left, ++a); createTree(n->right, ++a); } } void threadNode(Node* n) { if (n) { threadNode(n->left); if (!n->left) { // 左边为NULL n->leftThread = true; n->left = pre; } if (!pre->right) { pre->rightThread = true; pre->right = n; } pre = n; threadNode(n->right); } } public: BinaryTree(int a[]) { createTree(root, a); head = NULL; pre = NULL; } // 中序线索化 void threading() { head = (Node*) malloc(sizeof (Node)); head->left = head; head->right = head; head->leftThread = false; head->rightThread = true; if (root) { head->left = root; pre = head; threadNode(root); pre->right = head; pre->rightThread = true; head->right = pre; } } // 利用建立的线索遍历 void threadTraverse() { Node* n = head->left; while (n != head) { while (!n->leftThread) { n = n->left; } cout << n->i << endl; while (n->rightThread && n->right != head) { n = n->right; cout << n->i << endl; } n = n->right; } } }; void testTree() { // int a[] = {1, 2, -1, 4, -1, -1, 3, -1, -1}; // -1表示该位置空 int a[] = {1, 2, 4, 8, -1, -1, 9, -1, -1, 5, 10, -1, -1, -1, 3, 6, -1, -1, 7, -1, -1}; BinaryTree tree(a); tree.threading(); tree.threadTraverse(); }
相关文章推荐
- 二叉树的遍历方法之层序-先序-中序-后序遍历的简单讲解和代码示例
- 网页爬虫的最简C/C++程序代码示例------先通过列表获取所有博文id, 然后遍历所有博文id
- C++实现二叉树及其线索化和遍历
- 二叉树的遍历方法之层序-先序-中序-后序遍历的简单讲解和代码示例
- 二叉树先中后序遍历的C++代码
- c++模板实现二叉树,线索化,线索化遍历,非递归遍历及一些基本操作
- 二叉树的先序建立与非递归遍历C++版
- 二叉树的建立与递归遍历C++版
- [转]C++语法概括及其示例(示例代码下载)
- 几个网络模型的示例代码(BlockingModel、OverlappedModel、WSAEventSelect、CompletionRoutine)..c++
- C++ 数据库连接代码示例
- C#中遍历枚举示例代码
- [C/C++] 先序建立二叉树| 先序、中序、后序遍历二叉树| 求二叉树深度、节点数、叶节点数 算法实现
- 递归示例(一):遍历二叉树
- 二叉树用顺序表实现 C++代码实现
- 二叉树的链式存储结构 C++代码实现
- 编程之美读书笔记_3.8 求二叉树中节点的最大距离 和 3.10分层遍历二叉树 相关代码
- 创建一个二叉树,对该树线索化,对该树线索化遍历
- C++语法概括及其示例(示例代码下载)
- shapefile格式说明及读写代码示例(C++)(转)