您的位置:首页 > 其它

二叉树转双向列表-仿写。

2016-05-26 15:39 369 查看
仿写了一个二叉树转双向列表。核心思想就是记录中序排序和缓存上一个指针。

#include "stdafx.h"
#include<stdlib.h>

struct BinanryTree
{
int value;
BinanryTree* p_left;
BinanryTree* p_right;
};

BinanryTree* insertTree(BinanryTree* p_tree, int value) {
if (p_tree == NULL) {
p_tree =(BinanryTree*) malloc(sizeof(BinanryTree));
memset(p_tree, 0, sizeof(BinanryTree)); /*初始化*/
p_tree->value = value;
return p_tree;
}
if (p_tree->value > value) {
p_tree->p_right=insertTree(p_tree->p_right, value);
}
else
{
p_tree-> p_left = insertTree(p_tree->p_left, value);
}
return p_tree;
}

/*对树中数据的操作*/
void operate(int value) {
printf("%d , ", value);
}

void show_tree(BinanryTree* p_tree) {
if (p_tree == NULL) {
return;
}
/*调换下面三个顺序,实现前中后序遍历*/
show_tree(p_tree->p_right);
operate(p_tree->value);
show_tree(p_tree->p_left);

}

void tree_to_list(BinanryTree* p_tree, BinanryTree* last_node) {
if (p_tree == NULL) {
return;
}
tree_to_list(p_tree ->p_left , last_node);

if (last_node != NULL) {
p_tree->p_left = last_node;
last_node->p_right = p_tree;
}
last_node = p_tree;

if (p_tree->p_right != NULL) {
tree_to_list(p_tree->p_right, last_node);
}

}

struct List
{
int value;
List* p_left;
List* p_right;

};

BinanryTree* get_head(BinanryTree* p_tree) {
if (p_tree == NULL) {
return NULL;
}

if (p_tree->p_right == NULL) {
return p_tree;
}
return get_head(p_tree->p_right);

}

void show_list(BinanryTree* p_list) {
if (p_list != NULL) {
printf("%d, ", p_list->value);
show_list(p_list->p_left);
}
}

int main()
{
int x[8] = {54, 23, 12, 42, 90, 3, 132, 89};
BinanryTree* p_tree = NULL;

for (int i = 0; i < 8; i++) {
p_tree = insertTree(p_tree, x[i]);

}

show_tree(p_tree);

BinanryTree* p_head = NULL;
BinanryTree* last_node = NULL;
p_head = get_head(p_tree);
tree_to_list(p_tree, last_node);
printf("\n\r");
show_list(p_head);
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: