详细思路
class Solution { public: void flatten(TreeNode* root) { if(!root)return ; vector<TreeNode*>nodes; dfs(root,nodes); int n=nodes.size(); for(int i=0;i<n-1;i++){ nodes[i]->left=nullptr; nodes[i]->right=nodes[i+1]; } nodes[n-1]->left=nullptr,nodes[n-1]->right=nullptr; return; } void dfs(TreeNode*root,vector<TreeNode*>&nodes){ if(!root)return ; nodes.push_back(root); dfs(root->left,nodes); dfs(root->right,nodes); } };
class Solution { public: void flatten(TreeNode* root) { TreeNode*cur=root; while(cur){ if(cur->left){ TreeNode*nex=cur->left,*pre=cur->left; while(pre->right)pre=pre->right; pre->right=cur->right; cur->left=nullptr; cur->right=nex; } cur=cur->right; } return; } };