1.把二元查找树转变成排序的双向链表 ****
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
首先我们定义的二元查找树 节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
题目:
输入一棵二元查找树,将该二元查找树转换成一个排序的双向链表。
要求不能创建任何新的结点,只调整指针的指向。
10
/ /
6 14
/ / / /
4 8 12 16
转换成双向链表
4=6=8=10=12=14=16。
首先我们定义的二元查找树 节点的数据结构如下:
struct BSTreeNode
{
int m_nValue; // value of node
BSTreeNode *m_pLeft; // left child of node
BSTreeNode *m_pRight; // right child of node
};
解答:
先序遍历,对于每个节点,它的做指针指向左子树的最右节点(左子树的最大节点),他的右指针指向右子树的最左节点(右子树的最小节点),首先要定位到这两个节点,但这两个节点的指针先不做调整,递归调用左子树和右子树后,再调整这两个节点,以保证程序能够正常执行,如果提前调整了这两个节点,左右子树的树结构就破坏了,运行会死循环出错。
下面是代码:
#include <stdio.h>
struct TreeNode {
int value_;
TreeNode* left_;
TreeNode* right_;
};
void Insert(TreeNode* &root, const int key) {
if (root == NULL) {
root = new TreeNode;
root->value_ = key;
root->left_ = NULL;
root->right_ = NULL;
return;
}
if (key >= root->value_) {
Insert(root->right_, key);
} else {
Insert(root->left_, key);
}
}
void Print(TreeNode* root) {
if (root) {
printf("%d ", root->value_);
} else {
return;
}
if (root->left_) {
Print(root->left_);
}
if (root->right_) {
Print(root->right_);
}
}
void ConvertToList(TreeNode*& root) {
TreeNode* left;
TreeNode* right;
if (root) {
left = root->left_;
right = root->right_;
TreeNode* left_most_right = left;
while (left_most_right && left_most_right->right_) {
left_most_right = left_most_right->right_;
}
root->left_ = left_most_right;
if (left) {
ConvertToList(left, head);
}
if (left_most_right) {
left_most_right->right_ = root;
}
TreeNode* right_most_left = right;
while (right_most_left && right_most_left->left_) {
right_most_left = right_most_left->left_;
}
root->right_ = right_most_left;
if (right) {
ConvertToList(right, head);
}
if (right_most_left) {
right_most_left->left_ = root;
}
}
}
int main(int argc, char** argv) {
int data[] = {10, 6, 14, 4, 8, 12, 16, 22, 3, 25, 74, 1, 18, 62, 7, 5};
TreeNode* root = NULL;
size_t size = sizeof(data)/sizeof(int);
for (int i = 0; i < size; ++i) {
Insert(root, data[i]);
}
// Print(root);
TreeNode * indexer = root;
ConvertToList(root);
while (indexer) {
printf("%d ", indexer->value_);
indexer = indexer->right_;
}
if (root) {
indexer = root->left_;
}
while (indexer) {
printf("%d ", indexer->value_);
indexer = indexer->left_;
}
}
参考文献:
http://www.360doc.com/content/07/0228/15/11586_379396.shtml
http://blog.csdn.net/qjt_uestc/article/details/6618022