题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
思路
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
/*
* 思路:按照中序遍历,把节点放进vector里,然后遍历一遍vector,重新分配指针
*/
class Solution {
private:
vector<TreeNode*> treelist;
void inOrder(TreeNode* root){
if(root != NULL){
inOrder(root->left);
treelist.push_back(root);
inOrder(root->right);
}
}
public:
TreeNode* Convert(TreeNode* pRootOfTree)
{
inOrder(pRootOfTree);
int len = treelist.size();
if(len == 0) return NULL;
if(len == 1) return pRootOfTree;
for(int i = 0; i < len; i++){
if(i == 0) {
treelist[i]->left = NULL;
treelist[i]->right = treelist[i+1];
}
else if(i == len-1) {
treelist[i]->left = treelist[i-1];
treelist[i]->right = NULL;
}
else{
treelist[i]->left = treelist[i-1];
treelist[i]->right = treelist[i+1];
}
}
return treelist[0];
}
};