您的位置:首页 > 编程语言 > C语言/C++

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: