题解 | #复杂链表的复制#
二叉搜索树与双向链表
http://www.nowcoder.com/practice/947f6eb80d944a84850b0538bf0ec3a5
中序遍历二叉树加入vector中,然后在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;
lmr(pRootOfTree);
for(int i=0;i!=v.size();i++){
if(i==0)
v[i]->left=nullptr;
else
v[i]->left=v[i-1];
if(i==v.size()-1)
v[i]->right=nullptr;
else
v[i]->right=v[i+1];
}
return v[0];
}
void lmr(TreeNode* root){
if(root->left) lmr(root->left);
v.emplace_back(root);
if(root->right) lmr(root->right);
}
};