题目大意:输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
九度OJ链接:http://ac.jobdu.com/problem.php?pid=1503
分析:二叉搜索树的中序序列是有序的,且每个节点有两个指针,这与双向链表很类似。利用二叉搜索树的中序有序性,可以以中序遍历树,同时记录遍历过的前一个节点,并修改成链表结构。二叉树的left指针指向前驱,right指针指向后继。
C++实现:
#include <iostream>
#include <stdio.h>
#include <vector>
#include <memory.h>
using namespace std;
struct Node
{
int value;
Node *left;
Node *right;
Node(int val)
{
value = val;
left = NULL;
right = NULL;
}
};
Node* createTree(Node *root)<span style="white-space:pre"> </span>// 通过前序方式构建链表
{
int ind = -1;
scanf("%d",&ind);
if(ind == 0)
{
return NULL;
}
root = new Node(ind);
root->left = createTree(root->left);
root->right = createTree(root->right);
return root;
}
Node *pre;
Node *head;
void buildDoubleLinkList(Node *root)
{
if(root == NULL)
return;
buildDoubleLinkList(root->left);
// cout<<root->value<<endl;
if(head == NULL)
{
pre = head = root;
}
else
{
pre->right = root;
root->left = pre;
pre = pre->right;
}
buildDoubleLinkList(root->right);
}
void input()
{
// freopen("c:/input.txt","r",stdin);
int n;
scanf("%d", &n);
for(int i = 0; i < n; i ++)
{
Node *root = NULL;
root = createTree(root);
pre = NULL;
head = NULL;
buildDoubleLinkList(root);
// bool tag = true;// 本题是每个节点后都输出一个空格,注意。
while(head)
{
// if(tag) tag = false;
// else
// cout<<" ";
cout<<head->value<<" ";
head = head->right;
}
cout<<endl;
}
}
int main()
{
input();
return 0;
}