数据结构 算法面试100题 之 二叉树转换成双向链表

本质上是对二叉树进行中序遍历。二叉树节点和链表节点使用同一个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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值