I wrote a code to figure out whether a small binary tree t1 is a subtree of t2.
I am supposed to get true
as the result but I am getting the opposite.
Here is my code:
class Node {
int val;
Node left, right;
public Node(int v) {
val = v;
left = right = null;
}
}
public class BT {
Node root;
public BT() {
root = null;
}
public boolean containsTree(Node t1, Node t2) {
StringBuilder s1 = new StringBuilder();
StringBuilder s2 = new StringBuilder();
getOrderString(t1, s1);
getOrderString(t2, s2);
return s1.indexOf(s2.toString()) != -1;
}
public void getOrderString(Node t, StringBuilder s) {
if (t == null) {
s.append("X");
return;
}
s.append(t.val);
getOrderString(t.left, s);
getOrderString(t.right, s);
}
public static void main(String[] args) {
BT bt = new BT();
bt.root = new Node(10);
bt.root.left = new Node(12);
bt.root.right = new Node(15);
bt.root.left.left = new Node(25);
bt.root.left.right = new Node(30);
bt.root.right.left = new Node(36);
BT bt2 = new BT();
bt2.root = new Node(10);
bt2.root.left = new Node(12);
bt2.root.right = new Node(15);
bt2.root.left.left = new Node(25);
System.out.println(bt.containsTree(bt.root, bt2.root));
}
}
Could anyone explain to me why i am getting false?
2nd tree is not the subtree of 1st one. That's why it returns false so your code is actually correct :)