Created
July 16, 2016 22:24
-
-
Save jianminchen/082118552020666ec5c794d1383b6ae8 to your computer and use it in GitHub Desktop.
flatten - facebook code lab - C++ solution provided by author - iterative solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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