-
题目描述:
-
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
-
输入:
-
输入可能包含多个测试样例。
对于每个测试案例,输入的第一行为一个数n(0<n<1000),代表测试样例的个数。
接下来的n行,每行为一个二叉搜索树的先序遍历序列,其中左右子树若为空则用0代替。
-
输出:
-
对应每个测试案例,
输出将二叉搜索树转换成排序的双向链表后,从链表头至链表尾的遍历结果。
-
样例输入:
-
1 2 1 0 0 3 0 0
-
样例输出:
-
1 2 3
#include <iostream>
#include <cstdio>
#include <cstring>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int a[1000],cnt;
struct Node
{
int x;
struct Node *left;
struct Node *right;
};
void createTree(Node *&root){
int x;
scanf("%d",&x);
if(!x)
root = NULL;
else{
root = new Node;
root->x = x;
createTree(root->left);
createTree(root->right);
}
}
void convert(Node *root,Node *&last){
if(root == NULL)
return;
Node *p = root;
if(p->left != NULL){
convert(p->left,last);
}
p->left = last;
if(last != NULL)
last->right = p;
last = p;
if(p->right != NULL)
convert(p->right,last);
}
int main(int argc, char const *argv[])
{
int n;
while(scanf("%d",&n) != EOF){
while(n--){
Node *root,*head,*last,*p;
last = NULL;
createTree(root);
convert(root,last);
head = last;
while(head != NULL && head->left != NULL)
head = head->left;
p = head;
while(p){
printf("%d ",p->x);
p = p->right;
}
printf("\n");
}
}
return 1;
}