Answer to Question #204107 in Java | JSP | JSF for Zahra

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.


1
Expert's answer
2021-06-06T23:44:55-0400
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!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS