剑指offer26——二叉搜索树与双向链表
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
简单的想法:由于二叉搜索树的中序遍历是顺序的,把结果放入数组中后再把左右孩子连接起来就完成了
/*
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;
if(pRootOfTree->left==NULL&&pRootOfTree->right==NULL)
return pRootOfTree;
vector<TreeNode*> vec;
inorder(vec,pRootOfTree);
for(int i=0;i<vec.size();i++) //把排好序的数组连接起来
{
if(i==0)
{
vec[i]->right=vec[i+1];
continue;
}
if(i==vec.size()-1)
{
vec[i]->left=vec[i-1];
continue;
}
vec[i]->left=vec[i-1];
vec[i]->right=vec[i+1];
}
return vec[0];
}
void inorder(vector<TreeNode*>& vec,TreeNode* pRoot) //中序遍历结果放入数组中
{
if(pRoot==NULL)
return;
inorder(vec,pRoot->left);
vec.push_back(pRoot);
inorder(vec,pRoot->right);
}
};