algorithm - Reversing Alternate Levels of a perfect binary tree -
the problem statement is:
given perfect binary tree, reverse alternate level nodes of binary tree.
given tree: / \ b c / \ / \ d e f g / \ / \ / \ / \ h j k l m n o modified tree: / \ c b / \ / \ d e f g / \ / \ / \ / \ o n m l k j h
solution 3 this site provides particularly elegant solution in uses swap method on nodes of numbered levels of tree:void
preorder(struct node *root1, struct node* root2, int lvl) { // base cases if (root1 == null || root2==null) return; // swap subtrees if level if (lvl%2 == 0) swap(root1->key, root2->key); // recur left , right subtrees (note : left of root1 // passed , right of root2 in first call , opposite // in second call. preorder(root1->left, root2->right, lvl+1); preorder(root1->right, root2->left, lvl+1); } // function calls preorder() left , right children // of root void reversealternate(struct node *root) { preorder(root->left, root->right, 0); }
for reason, though, when in order traversals of original , modified versions of tree printed, yield same output:
inorder traversal of given tree h d b j e k l f m c n g o inorder traversal of modified tree h d b j e k l f m c n g o
for reason, writers of article didn't recognize issue , left final solution shortest of 3 methods i'm assuming. method 2 in post longer, produces correct output.
is there bug solution causing output both versions of tree same?
is there bug solution causing output both versions of tree same?
there no bug algorithm. bug main
function never calls reversealternate()
, prints same tree twice.
add missing call (line 76 in link), , works perfectly.
Comments
Post a Comment