STRUCTURALLY IDENTICAL (BINARY TREE) giving 1 WA

Problem statement - Given two trees check if they are structurally identically

My code -
import java.util.*;
public class Main {

static Scanner scn = new Scanner(System.in);

public static void main(String[] args) {
	Main m = new Main();
	BinaryTree bt1 = m.new BinaryTree();
	BinaryTree bt2 = m.new BinaryTree();
	System.out.println(bt1.structurallyIdentical(bt2));
}

private class BinaryTree {
	private class Node {
		int data;
		Node left;
		Node right;
	}

	private Node root;
	private int size;

	public BinaryTree() {
		this.root = this.takeInput(null, false);
	}

	public Node takeInput(Node parent, boolean ilc) {

		int cdata = scn.nextInt();
		Node child = new Node();
		child.data = cdata;
		this.size++;

		// left
		boolean hlc = scn.nextBoolean();

		if (hlc) {
			child.left = this.takeInput(child, true);
		}

		// right
		boolean hrc = scn.nextBoolean();

		if (hrc) {
			child.right = this.takeInput(child, false);
		}

		// return
		return child;
	}

	public boolean structurallyIdentical(BinaryTree other) {
		return this.structurallyIdentical(this.root, other.root);
	}

	private boolean structurallyIdentical(Node tnode, Node onode) {
		// write your code here
		if(tnode!=null&&onode!=null){
		    return tnode.data==onode.data && structurallyIdentical(tnode.left,onode.left) && structurallyIdentical(tnode.right,onode.right);
		}
		if(tnode==null &&onode==null){
		    return true;
		}
		return false;
	}

}

}

The code is giving 1 WA out of 4 cases (rest are AC).

in this ques you don’t need to check the equality of node’s data…you just need to check for identical structure…so just remove the condition where you are checking the equality of data…rest code seems fine…

1 Like

Hi Aditya
As you are not responding to this thread, I am marking your doubt as Resolved for now. Re-open it if required.

Please mark your doubts as resolved in your course’s “ Ask Doubt ” section, when your doubt is resolved.