Convert binary tree to mirror tree in java
Java program for Convert binary tree to mirror tree. Here problem description and other solutions.
/*
Java program for
Convert binary tree to it's mirror tree
*/
// Binary Tree Node
class TreeNode
{
public int data;
public TreeNode left;
public TreeNode right;
public TreeNode(int data)
{
// Set node value
this.data = data;
this.left = null;
this.right = null;
}
}
public class BinaryTree
{
public TreeNode root;
public BinaryTree()
{
// Set initial values
this.root = null;
}
// Display inorder element
public void inorder(TreeNode node)
{
if (node != null)
{
inorder(node.left);
// Print node value
System.out.print(" " + node.data);
inorder(node.right);
}
}
// Convert binary tree into mirror tree
public void mirrorTree(TreeNode node)
{
if (node != null)
{
mirrorTree(node.left);
mirrorTree(node.right);
// Change left and right child
TreeNode temp = node.left;
node.left = node.right;
node.right = temp;
}
}
public static void main(String[] args)
{
// Create new tree
BinaryTree tree = new BinaryTree();
/* Binary Tree
-----------------------
1
/ \
6 8
/ \ / \
2 3 4 5
/ \
19 10
*/
// Add element
tree.root = new TreeNode(1);
tree.root.left = new TreeNode(6);
tree.root.left.left = new TreeNode(2);
tree.root.right = new TreeNode(8);
tree.root.right.right = new TreeNode(5);
tree.root.right.left = new TreeNode(4);
tree.root.left.right = new TreeNode(3);
tree.root.left.left.left = new TreeNode(19);
tree.root.right.right.right = new TreeNode(10);
System.out.print("\n Before convert");
System.out.print("\n In-order Data : ");
tree.inorder(tree.root);
// Transform into mirror tree
tree.mirrorTree(tree.root);
/*
Mirror Tree
--------------
1
/ \
8 6
/ \ / \
5 4 3 2
/ \
10 19
*/
System.out.print("\n After convert");
System.out.print("\n In-order Data : ");
tree.inorder(tree.root);
}
}
Output
Before convert
In-order Data : 19 2 6 3 1 4 8 5 10
After convert
In-order Data : 10 5 8 4 1 3 6 2 19
Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.
New Comment