Sunday, November 30, 2014

Flatten Binary Tree to Linked List

//iterative
void flatten(TreeNode *root) {
    while ( root ) {
        if ( root->left ) {
            TreeNode *ptr = root->left;
            while ( ptr->right ) ptr = ptr->right;
            ptr->right = root->right;
            root->right = root->left;
            root->left = NULL;
        }
        root = root->right;
    }
}

//recursive
void flatten(TreeNode *root) {
    if (!root) return;

    TreeNode* left = root->left;
    TreeNode* right = root->right;

    if (left) {
        root->right = left;
        root->left = NULL;

        TreeNode* rightmost = left;
        while(rightmost->right) {rightmost = rightmost->right;}
        rightmost->right = right; //the right most points  to the original right child
    }

    flatten(root->right); //tail recursion        
}

No comments:

Post a Comment