Question #204107

Write a program that's define two binary trees to be identical if either both are empty, or their roots are

equal, their left subtrees are identical, and their right subtrees are identical.


Expert's answer

class Node 
{
    int d;
    Node lt, rt;
   
    Node(int n) 
    {
        d = n;
        lt = rt = null;
    }
}
   
class Binary_tree 
{
    Node r1, r2;
    boolean identical_trees(Node x, Node y) 
    {
        if (x == null && y == null)
            return true;
        if (x != null && y != null) 
            return (x.d == y.d && identical_trees(x.lt, y.lt) && identical_trees(x.rt, y.rt));
        return false;
    }


    public static void main(String[] args) 
    {
        Binary_tree t = new Binary_tree();
   
        t.r1 = new Node(5);
        t.r1.lt = new Node(6);
        t.r1.rt = new Node(7);
        t.r1.lt.lt = new Node(8);
        t.r1.lt.rt = new Node(9);
   
        t.r2 = new Node(5);
        t.r2.lt = new Node(6);
        t.r2.rt = new Node(7);
        t.r2.lt.lt = new Node(8);
        t.r2.lt.rt = new Node(9);
   
        if (t.identical_trees(t.r1, t.r2))
            System.out.println("Identical");
        else
            System.out.println("NOT Identical");
   
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS