输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
// ConsoleApplication2.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include "stdafx.h"
#include<iostream>
#include<vector>
#include<algorithm>
#include<numeric>
#include<list>
#include<iterator>
#include<queue>
#include<stack>
#include<algorithm>
#include<forward_list>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};
class Solution {
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
if (pRootOfTree == NULL) return NULL;
vec.clear();
node.clear();
InOrderTraversData(pRootOfTree);
InOrderTraversNode(pRootOfTree);
auto valIt = vec.begin();
auto nodeIt = node.begin();
TreeNode *head=*(node.begin()); //初始化头节点
TreeNode *pre;
head->left = NULL;
head->right = NULL;
head->val = *(vec.begin());
pre = head; //pre指向头节点
while (++valIt != vec.end() && ++nodeIt != node.end()) //将节点值赋值个node中的节点
{
pre->right = *(nodeIt);
(*nodeIt)->left = pre;
(*nodeIt)->val = *valIt;
pre = *nodeIt;
}
pre->right = NULL;
return head;
}
void printLinkL_R(TreeNode *T) //打印 测试程序是否正确
{
cout << "从左往右打印:" << endl;
while (T->right != NULL)
{
cout << T->val << " ";
T = T->right;
}
cout << T->val << " ";
cout << endl;
cout << "从右往左打印:" << endl;
while (T->left != NULL)
{
cout << T->val << " ";
T = T->left;
}
cout << T->val << " ";
cout << endl;
}
vector<TreeNode *> node;
void InOrderTraversNode(TreeNode* T)//中序遍历得到节点的值
{
if (T == NULL) return;
else
{
InOrderTraversNode(T->left);
node.push_back(T);
InOrderTraversNode(T->right);
}
}
vector<int> vec;
void InOrderTraversData(TreeNode* T) //中序遍历得到T的值
{
if (T == NULL) return;
else
{
InOrderTraversData(T->left);
vec.push_back(T->val);
InOrderTraversData(T->right);
}
}
void print() //中序打印
{
for (auto it = vec.begin(); it != vec.end(); ++it)
cout << *it<<" ";
cout << endl;
}
void preCreate(TreeNode* &T) //前序创建
{
int num;
cin >> num;
if (num == 0) return;
else
{
T = new TreeNode(num);
preCreate(T->left);
preCreate(T->right);
}
}
};
int main()
{
Solution so;
TreeNode *T=NULL;
TreeNode *copy = NULL;
so.preCreate(T);
cout << "创建二叉树成功!"<<endl;
cout << "中序遍历的结果:" << endl;
//so.InOrderTraversData(T);
//so.print();
copy = so.Convert(T);
so.printLinkL_R(copy);
// so.print();
cout << endl;
return 0;
}