sundeepblue
3/17/2014 - 6:12 PM

flatten a binary tree to a linked list in-place.

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;
    }
}