时间限制:1秒空间限制:32768K热度指数:6676
**算法知识视频讲解
题目描述
输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
题解:双向链表,先通过中序遍历获得顺序
然后遍历vector得到右边,然后再往左遍历
代码如下:
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<TreeNode*>v;
TreeNode* Convert(TreeNode* pRootOfTree)
{
if(pRootOfTree==NULL)return NULL;
inordered(pRootOfTree);
for(int i=0;i<v.size();++i){
if(i==0){
pRootOfTree=v[i];
}else{
pRootOfTree->right=v[i];
pRootOfTree=pRootOfTree->right;
}
}
for(int i=v.size()-2;i>=0;--i){
pRootOfTree->left=v[i];
pRootOfTree=pRootOfTree->left;
}
return pRootOfTree;
}
void inordered(TreeNode* pRootOfTree){
if(pRootOfTree==NULL)return;
inordered(pRootOfTree->left);
v.push_back(pRootOfTree);
inordered(pRootOfTree->right);
}
};