题目要求
思路
1.观察给的用例,本质上是把数据按照中序遍历连接起来
2.将结点以中序遍历的方式插入到数组中,注意这里是vector
3.将数组中的数据连接起来
代码实现
/*
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
TreeNode(int x) :
val(x), left(NULL), right(NULL) {
}
};*/
class Solution {
public:
vector<TreeNode*> res;
TreeNode* Convert(TreeNode* pRootOfTree) {
if (pRootOfTree == nullptr)
return nullptr;
midorder(pRootOfTree);
for(int i = 0; i < res.size()-1; i++)
{
res[i]->right = res[i+1];
res[i+1]->left = res[i];
}
return res[0];
}
void midorder(TreeNode* pRootOfTree)
{
if (pRootOfTree == nullptr)
return;
midorder(pRootOfTree->left);
res.push_back(pRootOfTree);
midorder(pRootOfTree->right);
}
};