首页 > 代码库 > 数据结构:中序线索二叉树

数据结构:中序线索二叉树



//所谓线索二叉树无非是为了让原本指向NULL的节点指向一个详细的
//已经存在的节点,逻辑上实现指针的无空指向的实现。以下是我中
//序线索二叉树的实现。还是把先序线索二叉树与后序线索分开来写吧。

#include<iostream>
using namespace std;

template<typename Type>
struct Node
{
    Type data;
    bool rflags;//false为线。

bool lflags; Node<Type> *right; Node<Type> *left; Node(Type d = Type()) :data(d), right(NULL), left(NULL), lflags(false),rflags(false){} }; template<typename Type> class MyTree { public: MyTree() :root(NULL){} void Create_lvr_lrv(Type *LVR,Type *LRV) { int n = strlen(LRV); Create_lvr_lrv(root,LVR,LRV,n); } void Create_Thread_V()//中序构造线索二叉树。 { Node<Type> *pr = NULL; Create_Thread_V(root, pr); Node<Type> *p = root; while (p->right != NULL) { p = p->right; } p->right = NULL; p->rflags = true; } void Printf_V() { Node<Type> *p = root; while (p->left != NULL) { p = p->left; } Printf_V(p); } private: void Printf_V(Node<Type> *t)//中序线索二叉树的打印。 { Node<Type> *p = t; while (p != NULL) { cout << p->data << " "; Node<Type>*m = p->right; if (p->rflags != true) { while (m != NULL && m->lflags != true) { m = m->left; } } p=m; } } void Create_Thread_V(Node<Type> *t, Node<Type> *&pr) { if (t == NULL) { return; } Create_Thread_V(t->left, pr); if (t->left== NULL) { t->left = pr; t->lflags = true; } if (pr!=NULL && pr->right ==NULL) { pr->right = t; pr->rflags = true; } pr = t; Create_Thread_V(t->right,pr); } void Create_lvr_lrv(Node<Type> *&t, Type *LVR, Type *LRV, int n) { if (n == 0)return; int i = 0; while (LRV[n - 1] != LVR[i])i++; t = new Node<Type>(LRV[n - 1]); Create_lvr_lrv(t->right,LVR+i+1,LRV+i,n-i-1); //依据中序及后序构造二叉树,此处我选择先构造右子树,然后才构造左子树。 Create_lvr_lrv(t->left,LVR,LRV,i); } private: Node<Type> *root; }; int main() { char LVR[] = "CBDAFEG"; char LRV[] = "CDBFGEA"; MyTree<char> mt; mt.Create_lvr_lrv(LVR,LRV); mt.Create_Thread_V(); mt.Printf_V(); return 0; }

技术分享

<script type="text/javascript"> $(function () { $(‘pre.prettyprint code‘).each(function () { var lines = $(this).text().split(‘\n‘).length; var $numbering = $(‘
    ‘).addClass(‘pre-numbering‘).hide(); $(this).addClass(‘has-numbering‘).parent().append($numbering); for (i = 1; i <= lines; i++) { $numbering.append($(‘
  • ‘).text(i)); }; $numbering.fadeIn(1700); }); }); </script>

数据结构:中序线索二叉树