先中序遍历把各个节点压入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 pRootOfTree;
PushTov(pRootOfTree);
for(int i=0;i<v.size()-1;i++)
v[i]->right=v[i+1];
v[v.size()-1]->right=NULL;
for(int i=v.size()-1;i!=0;i--)
v[i]->left=v[i-1];
v[0]->left=NULL;
return v[0];
}
void PushTov(TreeNode* pRootOfTree)
{
TreeNode* pNode=pRootOfTree;
if(pNode!=NULL)
{
PushTov(pNode->left);
v.push_back(pNode);
PushTov(pNode->right);
}
}
};