126k views
3 votes
Write a Java Program to find if two Binary Search Trees are identical or not?

User Dantz
by
8.1k points

1 Answer

7 votes

Final answer:

To determine if two binary search trees (BSTs) are identical in Java, we can use a recursive approach. We compare the values of the nodes in both trees and recursively check their left and right subtrees. If the values of the current nodes are equal and the left and right subtrees are also identical, we can conclude that the BSTs are identical.

Step-by-step explanation:

To determine if two binary search trees (BSTs) are identical in Java, we can use a recursive approach. We compare the values of the nodes in both trees and recursively check their left and right subtrees. If the values of the current nodes are equal and the left and right subtrees are also identical, we can conclude that the BSTs are identical. Here is an example of a Java program to solve this:

class Node {
int value;
Node left;
Node right;
Node(int value) {
this.value = value;
left = null;
right = null;
}
}
class IdenticalBSTs {
// Function to check if two BSTs are identical
static boolean areIdentical(Node root1, Node root2)
// Base case: If both trees are empty
if (root1 == null && root2 == null)
return true;
// Base case: If only one tree is empty
if (root1 == null
// Driver code
public static void main(String[] args) {
Node root1 = new Node(5);
root1.left = new Node(3);
root1.right = new Node(7);
root1.left.left = new Node(1);
root1.left.right = new Node(4);
root1.right.left = new Node(6);
Node root2 = new Node(5);
root2.left = new Node(3);
root2.right = new Node(7);
root2.left.left = new Node(1);
root2.left.right = new Node(4);
root2.right.left = new Node(6);
if (areIdentical(root1, root2))
System.out.println("BSTs are identical");
else
System.out.println("BSTs are not identical");
}
}

User Dahernan
by
8.9k points