Skip to content

Instantly share code, notes, and snippets.

@xiren-wang
Created August 31, 2014 07:02
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 xiren-wang/9a6dec35c7676b7da5a7 to your computer and use it in GitHub Desktop.
Save xiren-wang/9a6dec35c7676b7da5a7 to your computer and use it in GitHub Desktop.
Flatten Binary Tree to Linked List
/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}\ 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
* };
*/
class Solution {
public:
void flatten(TreeNode *root) {
//root -> leftSon -> ... -> lastLeft -> right -> ... -> lastRight
if (!root)
return;
TreeNode *last=NULL;
root = flatten(root, last);
return ;
}
TreeNode *flatten(TreeNode *root, TreeNode *&last) {
TreeNode *left = root->left; root->left = NULL;
TreeNode *right = root->right; root->right = NULL;
TreeNode *lastLeft=NULL;
if (left) {
root->right = flatten (left, lastLeft);
}
TreeNode *lastRight=NULL;
if (right) {
if (lastLeft)
lastLeft->right = flatten (right, lastRight);
else
root->right = flatten(right, lastRight);
}
//update last
if (lastRight)
last = lastRight;
else if (lastLeft)
last = lastLeft;
else
last = root;
return root;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment