voidflatten(TreeNode* root){ if (root==NULL) return ; flatten(root->left); flatten(root->right); auto right = root->right; auto left = root->left; if (left){ root->right = left; root->left = NULL; while(left->right) left = left->right; left->right = right; } }
TreeNode *last; voidflatten(TreeNode* root){ if (root==NULL) return ; flatten(root->right); flatten(root->left); root->right = last; root->left = nullptr; last = root; }
然后是在dicuss中看到的迭代算法:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
voidflatten(TreeNode *root){ while (root) { if (root->left && root->right) { TreeNode* t = root->left; while (t->right) t = t->right; t->right = root->right; }