 JAVA EXAMPLE PROGRAMS

Publish Your Article Here

Program: Write a program to find given two trees are mirror or not.

 Description: Write a simple program to identify given two binary trees are mirrored image of each other. Here is an example image of mirrored trees: Here are the steps to find out mirrored binary trees: If both given trees root node values are same. Left subtree of root of first tree is mirror of right subtree of root of second tree. Right subtree of root of first tree is mirror of left subtree of root of second tree.

 MirrorTreesEx.java package com.java2novice.ds.trees; public class MirrorTreesEx { public static boolean areMirrorTrees(Node a_root, Node b_root) { /** * Recursion exist condition - 1 * When both nodes are null, return true */ if(a_root == null && b_root == null) { return true; } /** * Recursion exist condition - 2 * When one of the node is null, return false */ if(a_root == null || b_root == null) { return false; } return a_root.data == b_root.data && areMirrorTrees(a_root.left, b_root.right) && areMirrorTrees(a_root.right, b_root.left); } public static void main(String arg[]) { BinaryTree a = new BinaryTree(); a.root = new Node(5); a.root.left = new Node(6); a.root.right = new Node(7); a.root.left.left = new Node(8); a.root.left.right = new Node(9); BinaryTree b = new BinaryTree(); b.root = new Node(5); b.root.left = new Node(7); b.root.right = new Node(6); b.root.right.left = new Node(9); b.root.right.right = new Node(8); System.out.println("Is Mirror Trees? "+MirrorTreesEx.areMirrorTrees(a.root, b.root)); BinaryTree a1 = new BinaryTree(); a1.root = new Node(5); a1.root.left = new Node(6); a1.root.right = new Node(7); a1.root.left.left = new Node(8); a1.root.left.right = new Node(9); BinaryTree b1 = new BinaryTree(); b1.root = new Node(5); b1.root.left = new Node(7); b1.root.right = new Node(6); b1.root.right.left = new Node(9); System.out.println("Is Mirror Trees? "+MirrorTreesEx.areMirrorTrees(a1.root, b1.root)); } }

 Output: Is Mirror Trees? true Is Mirror Trees? false

List Of All Interview Programs:

Java2Novice - YouTube Channel
Knowledge Centre
What is OOPs?
Object oriented programming organizes a program around its data, i.e. , objects and a set of well defined interfaces to that data. An object-oriented program can be characterized as data controlling access to code.
Famous Quotations
The pessimist complains about the wind; the optimist expects it to change; the realist adjusts the sails.
-- William Arthur Ward

Other Interesting Sites

 Reference: Java™ Platform Standard Ed. 7 - API Specification | Java™ Platform Standard Ed. 8 - API Specification | Java is registered trademark of Oracle. Privacy Policy | Copyright © 2019 by Nataraja Gootooru. All Rights Reserved.