Last active
March 14, 2016 02:04
-
-
Save sundeepblue/9605004 to your computer and use it in GitHub Desktop.
flatten a binary tree to a linked list in-place.
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
| 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