Created
February 26, 2013 22:41
-
-
Save zhoutuo/5043027 to your computer and use it in GitHub Desktop.
Given a binary tree, flatten it to a linked list in-place. For example,
Given 1 / \ 2 5 / \ \ 3 4 6
The flattened tree should look like: 1 \ 2 \ 3 \ 4 \ 5 \ 6
This file contains hidden or 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
/** | |
* Definition for binary tree | |
* struct TreeNode { | |
* int val; | |
* TreeNode *left; | |
* TreeNode *right; | |
* TreeNode(int x) : val(x), left(NULL), right(NULL) {} | |
* }; | |
*/ | |
class Solution { | |
public: | |
void flatten(TreeNode *root) { | |
// Start typing your C/C++ solution below | |
// DO NOT write int main() function | |
if(root == NULL) { | |
return; | |
} else if(root->left == NULL and root->right == NULL) { | |
return; | |
} else { | |
flatten(root->left); | |
flatten(root->right); | |
if(root->left != NULL) { | |
TreeNode* last = root->left; | |
while(last->right != NULL) { | |
last = last->right; | |
} | |
last->right = root->right; | |
root->right = root->left; | |
root->left = NULL; | |
} | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment