Question: Mirror of a Binary Tree T is another Binary Tree M(T) with left and
right children of all non-leaf nodes interchanged.
Algorithm -
Mirror(tree):
(1) Call Mirror for left-subtree i.e., Mirror(left-subtree)
(2) Call Mirror for right-subtree i.e., Mirror(left-subtree)
(3) Swap left and right subtrees.
temp = left-subtree
left-subtree = right-subtree
right-subtree = temp
(2) Call Mirror for right-subtree i.e., Mirror(left-subtree)
(3) Swap left and right subtrees.
temp = left-subtree
left-subtree = right-subtree
right-subtree = temp
void mirror(TreeNode T)
{
If(T != null) {
// do the subtrees recursively
mirror(T.left);
mirror(T.right);
// swap the pointers in this node
TreeNode temp = T.left;
T.left = T.right;
T.right = temp;
}
}
No comments:
Post a Comment