void double_tree(tree_node* T) { /* For each node in a binary search tree, create a new duplicate node, and insert the duplicate as the left child of the original node. The resulting tree should still be a binary search tree. So the tree... 2 / \ 1 3 Is changed to... 2 / \ 2 3 / / 1 3 / 1 */ if(T!=NULL) { tree_node * l_change_node = T -> left; tree_node * r_change_node = T ->right; tree_node * add_node = new tree_node(T->data); add_node -> left = T->left; T->left = add_node; double_tree(l_change_node); double_tree(r_change_node); } }
void double_tree(bst *b) { if(!b) return; bst *dup = new_tree(b->val); dup->left = b->left; b->left = dup; if(b->left->left) double_tree(b->left->left); if(b->right) double_tree(b->right); }
//left sided doubling or one sided doubling void double_tree(bst *root) { bst *oldptr; if(root == 0) return; //NOTE : Here we do not return anything we utilize stack //feature not to avoid communication double_tree(root->left); double_tree(root->right); //store the in oldptr oldptr = root->left; //Update load new root->left = insert_node(root->data); //store old again for consistency purpose restore the old value root->left->left = oldptr; //we cannot use above tric in faltten as we know that we have to suplicate the strucutre only once but in flatten example we have to make count about how many levels/count we should maintain in order to append the data i.e. right pointer/old_ptr }
int main(int argc, char *argv[]) { struct bitree *tree; int cnt; tree = build(DEFAULT_TREE_SIZE); if (!tree) { fprintf(stderr, "build tree error\n"); exit(EXIT_FAILURE); } traverse_dump(tree, TRAVE_PREORDER); traverse_dump(tree, TRAVE_INORDER); traverse_dump(tree, TRAVE_POSTORDER); traverse_dump(tree, TRAVE_LEVELORDER); fprintf(stdout, "\nmirroring the tree\n"); mirror(tree->root); traverse_dump(tree, TRAVE_LEVELORDER); mirror(tree->root); /* reverse */ fprintf(stdout, "\ndoubling the tree\n"); double_tree(tree); traverse_dump(tree, TRAVE_LEVELORDER); traverse_dump(tree, TRAVE_INORDER); traverse_dump(tree, TRAVE_PREORDER); cnt = print_paths(tree->root); fprintf(stdout, "total %d paths\n", cnt); exit: if (visit_list) dlist_destroy(visit_list); free(bitree_root(tree)->data); bitree_destroy(tree); free(tree); exit(EXIT_SUCCESS); }