Java program to determine whether two trees are identical

In this program, we need to check whether two trees are identical or not. For two trees to be identical, they have to satisfy two conditions:

  • Structure of both the trees should be the same.
  • Nodes present in one tree should be present in another tree.
Java program to determine whether two trees are identical

Above diagram contains three trees namely A, B, and C. Trees A and B are the identical as they are structurally same and values of all nodes are the same. However, trees A and C are structurally same but not identical as nodes are different in both the trees.

Algorithm

  • Define Node class which has three attributes namely: data left and right. Here, left represents the left child of the node and right represents the right child of the node.
  • When a node is created, data will pass to data attribute of the node and both left and right will be set to null.
  • Define another class which has an attribute root.
    • Root represents the root node of the tree and initializes it to null.
  • areIdenticalTrees() will check whether two trees are identical or not:
    • If root nodes of both the trees are null then, they are identical.
    • If the root node of only one tree is null then, trees are not identical, return false.
    • If root node of none of the tree is null, then check whether data of both the nodes are equal and then recursively check the left subtree and right subtree of one tree is identical to another or not.

Program:

Output:

Both the binary trees are identical
Next TopicJava Programs




Latest Courses