Skip to content

Instantly share code, notes, and snippets.

@sundeepblue
Last active March 14, 2016 02:04
Show Gist options
  • Select an option

  • Save sundeepblue/9605004 to your computer and use it in GitHub Desktop.

Select an option

Save sundeepblue/9605004 to your computer and use it in GitHub Desktop.
flatten a binary tree to a linked list in-place.
http://stackoverflow.com/questions/15939582/flatten-binary-search-to-in-order-singly-linked-list-c
//========================================
// recursive. Code below is hard to read if no context. It implement in pre-order
// traversal, as shown in http://www.programcreek.com/2013/01/leetcode-flatten-binary-tree-to-linked-list/
void flatten(TreeNode *r) {
if(!r) return;
flatten(r->left);
if(r->left == NULL) return; // !!!
flatten(r->right);
TreeNode *p = r->left;
while(p->right) p = p->right;
p->right = r->right;
r->right = r->left;
r->left = NULL;
}
//========================================
// iterative
void flatten(TreeNode *r) {
while(r) {
if(r->left) {
TreeNode *p = r->left;
while(p->right) p = p->right;
p->right = r->right;
r->right = r->left;
r->left = NULL;
}
r = r->right;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment