Mirror Tree
In a binary tree, the left and right nodes are swapped which result produces the mirror view of a binary tree.
Binary Tree
A binary tree is a non-linear data structure in which every node has at a most maximum of two children. So, in terms of binary tree construction, we should have a node with three-pointers one to hold data and two for left and right nodes.
class Tree {
public class Node {
int data;
Node right;
Node left;
Node(int data) {
this.data = data;
left = right = null;
}
}
In this above tree class with inner node class has one instance member data and two objects of Node class left and right. For every new node, we use Node(int data ) constructor to assign data to that node and set left and right as null.
Tree.Node t = new Tree().new Node(1);
t.left = new Tree().new Node(2);
t.left.left = new Tree().new Node(4);
t.left.right = new Tree().new Node(5);
t.right = new Tree().new Node(3);
The traversal of the above binary tree results in 1 2 4 5 3
public void traversal(Node root) {
if (root.left != null) {
traversal(root.left);
}
System.out.print(root.data + " ");
if (root.right != null) {
traversal(root.right);
}
}
But on swapping the left node with the right on the same level it converts into a mirror tree.
public Node mirror(Node root) {
if (root == null)
return root;
Node left = mirror(root.left);
Node right = mirror(root.right);
root.left = right;
root.right = left;
return root;
}
In the above program in every recursive call the values are swapped which produces a mirror
view on traversal.
public void traversal(Node root) {
if (root.left != null) {
traversal(root.left);
}
System.out.print(root.data + " ");
if (root.right != null) {
traversal(root.right);
}
}
The mirror view of the binary tree is: 1 3 2 5 4
I hope you guys liked this article, here are some other articles you may like:
0 Comments