注意指针作为实参时传递的也是副本,若要修改指针则必须使用指针的指针或指针的引用
#include <iostream>
#include "conio.h"// 提供getch()设置断点using namespace std;
typedef struct btnode{
int value;
int ltag,rtag;
struct btnode *lchild;
struct btnode *rchild;
}btnode;
void createtree(btnode *&, int);
//void preorder(btnode *);
void inthreadtree(btnode *&,btnode *&);
void tra(btnode*);
btnode* first(btnode*);
btnode* next(btnode*);
int main(void)
{
btnode* root = new btnode;
int n;
cin>>n;
root->value = n;
root->ltag = 0; root->rtag = 0;
root->lchild = NULL;
root->rchild = NULL;
while(cin>>n)
createtree(root, n);
// preorder(root);
btnode* pre = NULL;
inthreadtree(root, pre);//传的只是指针的副本 pre也是副本导致线索并没有被连起来
tra(root);
return 0;
}
void createtree(btnode*& root, int n)
{
if(root != NULL) {
if(n < root->value) {
createtree(root->lchild, n);
}
else
createtree(root->rchild, n);
}
else {
root = new btnode;
root->value = n;
root->ltag = 0; root->rtag = 0;
root->lchild = NULL;
root->rchild = NULL;
}
}
/*void preorder(btnode* root)
{
if(root != NULL) {
cout<<root->value<<endl;
preorder(root->lchild);
preorder(root->rchild);
}
}*/
void inthreadtree(btnode*& root,btnode*& pre)
{
if(NULL != root) {
inthreadtree(root->lchild, pre);
if(NULL == pre) {
root->ltag = 1;
root->lchild = NULL;
}else {
if(pre->rchild == NULL) {
pre->rtag = 1;
pre->rchild = root;
}
if(root->lchild == NULL) {
root->ltag = 1;
root->lchild = pre;
}
}
pre = root;
inthreadtree(root->rchild, pre);
}
}
void tra(btnode* root)
{
btnode* p = first(root);
while(NULL != p) {
cout<<p->value<<",";
p = next(p);
}
}
btnode* first(btnode* root)
{
while(root->lchild != NULL && root->ltag == 0) root = root->lchild;
return root;
}
btnode* next(btnode* root)
{
if(root->rchild != NULL && root->rtag == 1) return root->rchild;
else return first(root->rchild);
}