Site icon

Convert binary tree to mirror/symmetric tree in java (recursive /example)

Fig 1: Example of binary trees (one or two children)

Examples – Convert binary tree to mirror or symmetric tree (recursive)

Example 1: Mirror binary tree having right child in java

Fig 2: Binary tree with left child node

Example 2: Symmetric binary tree having left child (recursive)

Fig 3: Binary tree with right child node

Example 3: image binary tree having left & right child (recursive).

Fig 4: Symmetric tree having left & right node

Algorithm: convert binary tree into mirror binary tree in java

Fig 5: Binary Tree & Mirror (Symmetric) Tree

Time complexity of algorithm will be O(n).

Program – convert binary tree to mirror or image or symmetric tree in java

1.) MirrorTree Class:

  package org.learn.Question;

import java.util.LinkedList;
import java.util.Queue;

public class MirrorTree {
	public static void mirrorTree(Node root) {
		if(null == root) {
			return;
		}
		mirrorTree(root.left);
		mirrorTree(root.right);
		Node swapNode = root.left;
		root.left = root.right;
		root.right = swapNode;
		return;
	}
	
	public static void printTree(Node root) {
		if (root == null) {
			System.out.println("Tree is empty");
			return ;
		}
		Queue queue = new LinkedList();
		queue.offer(root);
		while (!queue.isEmpty()) {
			Node node = queue.poll();			
			System.out.printf(" %d",node.data);		
			if (node.left != null) {
				queue.offer(node.left);
			}
			if (node.right != null) {
				queue.offer(node.right);
			}
		}
		System.out.println("");	
		return;
	}
}

2.) Node Class:

package org.learn.Question;

public class Node {
	public int data;
	public Node left;
	public Node right;

	public Node(int num) {
		this.data = num;
		this.left = null;
		this.right = null;
	}

	public Node() {
		this.left = null;
		this.right = null;
	}
	
	public static Node createNode(int number) {
		return new Node(number);
	}
}

3.) App Class: 

package org.learn.Client;

import org.learn.Question.MirrorTree;
import org.learn.Question.Node;

public class App {
	public static void main(String[] args) {
		// root level 0
		Node A = Node.createNode(55);
		// Level 1
		Node B = Node.createNode(50);
		Node C = Node.createNode(40);
		// Level 2
		Node D = Node.createNode(25);
		Node E = Node.createNode(80);
		Node F = Node.createNode(45);
		Node G = Node.createNode(90);

		// connect Level 0 and 1
		A.left = B;
		A.right = C;
		// connect level 1 and level 2
		B.left = D;
		B.right = E;
		C.left = F;
		C.right = G;
		
		System.out.println("Binary Tree");
		MirrorTree.printTree(A);
		MirrorTree.mirrorTree(A);
		System.out.println("Mirror Binary Tree");
		MirrorTree.printTree(A);
	}
}

Output – mirror or Symmetric binary tree in java (Fig 5):

Binary Tree : 
55 50 40 25 80 45 90 
Mirror Binary Tree : 
55 40 50 90 45 80 25 

Download code – convert mirror image of binary tree (recursive)

 

Exit mobile version