题目:输入一颗二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的节点,只能调整树中节点指针的指向。
分析:首先不能创建新的结构,只能在树的前提下进行改变指针的指向。又由于是二叉搜索树,可以通过画图分析可知,二叉搜索树的左子树小于根节点小于右子树,可以发现是个递归过程也是一个中序遍历。所以只需要在中序那块进行指针调整。
/*
剑指offer面试题27
*/
#include <iostream>using namespace std;
struct BinaryTree{
int data;
BinaryTree* lchild;
BinaryTree* rchild;
};void Convert(BinaryTree* root,BinaryTree** pList){
if(root == NULL){
return;
}BinaryTree* pTree = root;
if(pTree->lchild){
Convert(pTree->lchild,pList);
}// 双链表
pTree->lchild = *pList;
if(*pList != NULL){
(*pList)->rchild = pTree;
}
*pList = pTree;if(pTree->rchild){
Convert(pTree->rchild,pList);
}}
BinaryTree* Convert(BinaryTree* root){
BinaryTree* pList = NULL;
Convert(root,&pList);BinaryTree* pListHead = pList;
while(pListHead->lchild != NULL){
pListHead = pListHead->lchild;
}
return pListHead;
}BinaryTree* Create(){
BinaryTree* root = new BinaryTree;
root->data = 10;
BinaryTree* lchild = new BinaryTree;
lchild->data = 6;
BinaryTree* rchild = new BinaryTree;
rchild->data = 14;
root->lchild = lchild;
root->rchild = rchild;BinaryTree* lchild1 = new BinaryTree;
lchild1->data = 4;
BinaryTree* rchild1 = new BinaryTree;
rchild1->data = 8;
lchild->lchild = lchild1;
lchild->rchild = rchild1;BinaryTree* lchild2 = new BinaryTree;
lchild2->data = 12;
BinaryTree* rchild2 = new BinaryTree;
rchild2->data = 16;
rchild->lchild = lchild2;
rchild->rchild = rchild2;lchild1->lchild = NULL;
lchild1->rchild = NULL;
rchild1->lchild = NULL;
rchild1->rchild = NULL;lchild2->lchild = NULL;
lchild2->rchild = NULL;
rchild2->lchild = NULL;
rchild2->rchild = NULL;return root;
}int main(){
BinaryTree* root = Create();
BinaryTree* pList = Convert(root);while(pList->rchild != NULL){
cout << pList->data << " ";
pList = pList->rchild;
}
cout << endl;
while(pList->lchild != NULL){
cout << pList->data << " ";
pList = pList->lchild;
}return 0;
}
数据结构-二叉搜索树与双向链表