C++二叉树线索化并遍历的示例代码

来源:互联网 发布:java定义可变长度数组 编辑:程序博客网 时间:2024/06/03 19:58

线索化的意义:二叉树的一般遍历方式都是递归的方式,而递归使用栈,当递归深度比较大时,很耗资源。线索化就是通过一次递归遍历,建立结点的前驱和后继关系。然后以后遍历的时候按这种关系遍历,就不用递归了。下面给出自己写的可运行代码。

#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) { // 左边为NULLn->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();}


0 0