Created
June 30, 2017 09:02
-
-
Save anil477/d5b0161315079770d57762a162da4cf9 to your computer and use it in GitHub Desktop.
Check for identical tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Node | |
{ | |
int data; | |
Node left, right; | |
Node(int item) | |
{ | |
data = item; | |
left = right = null; | |
} | |
} | |
class BinaryTree | |
{ | |
Node root1, root2; | |
boolean identicalTrees(Node a, Node b) | |
{ | |
/*1. both empty */ | |
if (a == null && b == null) | |
return true; | |
/* 2. both non-empty -> compare them */ | |
if (a != null && b != null) | |
return (a.data == b.data | |
&& identicalTrees(a.left, b.left) | |
&& identicalTrees(a.right, b.right)); | |
/* 3. one empty, one not -> false */ | |
return false; | |
} | |
/* Driver program to test identicalTrees() function */ | |
public static void main(String[] args) | |
{ | |
BinaryTree tree = new BinaryTree(); | |
tree.root1 = new Node(1); | |
tree.root1.left = new Node(2); | |
tree.root1.right = new Node(3); | |
tree.root1.left.left = new Node(4); | |
tree.root1.left.right = new Node(5); | |
tree.root2 = new Node(1); | |
tree.root2.left = new Node(2); | |
tree.root2.right = new Node(3); | |
tree.root2.left.left = new Node(4); | |
tree.root2.left.right = new Node(5); | |
if (tree.identicalTrees(tree.root1, tree.root2)) | |
System.out.println("Both trees are identical"); | |
else | |
System.out.println("Trees are not identical"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment