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));
}
}
|