在中序遍历中调整:
static struct TreeNode* q=NULL; void order(struct TreeNode* p){ if(p->left) order(p->left); p->left=q; if(q) q->right=p; q=p; if(p->right) order(p->right); } struct TreeNode* Convert(struct TreeNode* pRootOfTree ) { // write code here if(!pRootOfTree) return NULL; order(pRootOfTree); while(pRootOfTree->left) pRootOfTree=pRootOfTree->left; return pRootOfTree; }存储中序遍历结点再连接:
class Solution { public: vector<TreeNode*> tree; vector<TreeNode*> order(TreeNode* p){ if(p->left) order(p->left); tree.push_back(p); if(p->right) order(p->right); return tree; } TreeNode* Convert(TreeNode* pRootOfTree) { if(!pRootOfTree) return NULL; order(pRootOfTree); for(int i=0;i<tree.size()-1;i++){ tree[i]->right=tree[i+1]; tree[i+1]->left=tree[i]; } return tree[0]; } };