代码
#include <stdio.h>
#include <stdlib.h>
#define CHILD 0
#define THREAD 1
typedef struct Node {
int val;
struct Node *left, *right;
int ltag, rtag;
} Node;
Node *initNode(int val) {
Node *n = (Node *)malloc(sizeof(Node));
n->val = val;
n->left = NULL, n->right = NULL;
n->ltag = CHILD, n->rtag = CHILD;
return n;
}
void freeNode(Node *p) {
if (!p) return ;
free(p);
return ;
}
Node *insertR(Node *root, int val) {
if (!root) return initNode(val);
if (val > root->val)
root->right = insertR(root->right, val);
else
root->left = insertR(root->left, val);
return root;
}
void insert(Node **raddr, int val) {
if (!(*raddr)) {
*raddr = initNode(val);
return ;
}
if (val > (*raddr)->val)
insert(&((*raddr)->right), val);
else
insert(&((*raddr)->left), val);
return ;
}
void freeAll(Node *root) {
if (!root) return ;
if (CHILD == root->ltag) freeAll(root->left);
if (CHILD == root->rtag) freeAll(root->right);
freeNode(root);
return ;
}
void inorderTrav(Node *root) {
if (!root) return ;
if (CHILD == root->ltag) inorderTrav(root->left);
printf("%d ", root->val);
if (CHILD == root->rtag) inorderTrav(root->right);
return ;
}
Node *pre = NULL;
void buildThread(Node *root) {
if (!root) return ;
buildThread(root->left);
if (!root->left)
root->left = pre, root->ltag = THREAD;
if (pre && !pre->right)
pre->right = root, pre->rtag = THREAD;
pre = root;
buildThread(root->right);
return ;
}
Node *getLeftMost(Node *p) {
while (p && CHILD == p->ltag && p->left)
p = p->left;
return p;
}
void outThread(Node *root) {
if (!root) return ;
Node *p = getLeftMost(root);
while (p) {
printf("%d ", p->val);
if (CHILD == p->rtag)
p = getLeftMost(p->right);
else p = p->right;
}
putchar(10);
return ;
}
int main() {
return 0;
}