首页 > 代码库 > 二元查找树转换成一个排序的双向链表
二元查找树转换成一个排序的双向链表
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
#ifndef UTILS_HEADER
#define UTILS_HEADER
#include "utils.h"
#endif
#include "MS.h"
struct treenode* MS01Util(struct treenode* root, int flag){
if (root == NULL){
return NULL;
}
struct treenode* left = MS01Util(root->lchild, 0);
struct treenode* right = MS01Util(root->rchild, 1);
if (left != NULL){
left->rchild = root;
root->lchild = left;
}
if (right != NULL){
right->lchild = root;
root->rchild = right;
}
struct treenode* result = root;
if (flag == 0){
while (root != NULL){
result = root;
root = root->rchild;
}
}
else{
while (root != NULL){
result = root;
root = root->lchild;
}
}
return result;
}
void MS01(){
double array[] = { 2, 3, 1, 5, 4, 2, 6, 3, 5, 1, 2, 4, 6, 3, 2, 1, 4 };
struct treenode* root = gene2OrTree(array, 17);
cout << endl;
root = MS01Util(root, 1);
while (root != NULL){
cout << root->value << " ";
root = root->rchild;
}
cout << endl;
return;
#define UTILS_HEADER
#include "utils.h"
#endif
#include "MS.h"
struct treenode* MS01Util(struct treenode* root, int flag){
if (root == NULL){
return NULL;
}
struct treenode* left = MS01Util(root->lchild, 0);
struct treenode* right = MS01Util(root->rchild, 1);
if (left != NULL){
left->rchild = root;
root->lchild = left;
}
if (right != NULL){
right->lchild = root;
root->rchild = right;
}
struct treenode* result = root;
if (flag == 0){
while (root != NULL){
result = root;
root = root->rchild;
}
}
else{
while (root != NULL){
result = root;
root = root->lchild;
}
}
return result;
}
void MS01(){
double array[] = { 2, 3, 1, 5, 4, 2, 6, 3, 5, 1, 2, 4, 6, 3, 2, 1, 4 };
struct treenode* root = gene2OrTree(array, 17);
cout << endl;
root = MS01Util(root, 1);
while (root != NULL){
cout << root->value << " ";
root = root->rchild;
}
cout << endl;
return;
}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。