本质上是对二叉树进行中序遍历。二叉树节点和链表节点使用同一个struct,只改变指针指向。
#include "stdio.h"
#include "stddef.h"#include "stdlib.h"
#include "assert.h"
struct s_node{
int value;
struct s_node *lNode;
struct s_node *rNode;
};
typedef struct s_node t_node;
struct s_list{
t_node *first;
t_node *last;
};
typedef struct s_list t_list;
void addToList(t_list *list, t_node *node){
assert(list != NULL && node != NULL);
if(list->last == NULL){ //no node in the list
assert(list->first == NULL);
node->lNode = NULL;
list->first = list->last = node;
} else{
list->last->rNode = node;
node->lNode = list->last;
list->last = node;
}
}
t_node* mallocNode(int value){
t_node *node = (t_node *)malloc(sizeof(t_node));
if(node != NULL){
node->value = value;
}
node->lNode = NULL;
node->rNode = NULL;
return node;
}
t_node* buildTree(){
t_node *root = mallocNode(8);
t_node *lNode = mallocNode(6);
t_node *rNode = mallocNode(10);
root->lNode = lNode;
root->rNode = rNode;
lNode->lNode = mallocNode(5);
lNode->rNode = mallocNode(7);
rNode->lNode = mallocNode(9);
rNode->rNode = mallocNode(11);
return root;
}
void deleteTree(t_node *root){
if(root == NULL) return;
if(root->lNode != NULL) deleteTree(root->lNode);
if(root->rNode != NULL) deleteTree(root->rNode);
free(root);
}
void TreeToList(t_node *root, t_list *list){
if(root == NULL) return;
if(root->lNode) TreeToList(root->lNode, list);
addToList(list, root);
if(root->rNode) TreeToList(root->rNode, list);
}
void printList(t_list *list){
t_node *currNode = list->first;
if(list == NULL || list->first == NULL || list->last == NULL) return;
while(currNode != NULL){
printf("%d ", currNode->value);
currNode = currNode->rNode;
}
printf("\n");
}
int main(){
t_node *root = buildTree();
t_list list;
list.first = list.last = NULL;
TreeToList(root, &list);
printList(&list);
deleteTree(root);
return 0;
}