Skip to content

Instantly share code, notes, and snippets.

@jianminchen
Created July 16, 2016 22:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jianminchen/082118552020666ec5c794d1383b6ae8 to your computer and use it in GitHub Desktop.
Save jianminchen/082118552020666ec5c794d1383b6ae8 to your computer and use it in GitHub Desktop.
flatten - facebook code lab - C++ solution provided by author - iterative solution
class Solution {
public:
void flatten(TreeNode *root) {
if (!root) return;
TreeNode* node = root;
while (node) {
// Attatches the right sub-tree to the rightmost leaf of the left sub-tree:
if (node->left) {
TreeNode *rightMost = node->left;
while (rightMost->right) {
rightMost = rightMost->right;
}
rightMost->right = node->right;
// Makes the left sub-tree to the right sub-tree:
node->right = node->left;
node->left = NULL;
}
// Flatten the rest of the tree:
node = node->right;
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment