Learn-dsa..in 30 days!



























CC-14 : Check if a given Binary Tree is a subtree of another Binary Tree.

Description:

A Binary Tree t1 a subtree of another Binary Tree bt2, if the root and all its sub nodes of t1 matches with a Tree Node t2 and all its sub nodes. Given 2 Binary Trees, check if the second Binary Tree t2 is a subtree of the first Binary Tree t1.

Test cases and expected outputs:

Input Parameters Expected outputs

Orig tree inOrder
33,6,5,78,4,8,14,9,18,16,7, toCheck tree inOrder
33,6,5,78, Orig tree preOrder
4,5,6,33,78,7,14,8,16,18,9, toCheck tree preOrder
5,6,33,78,

Is Check1 subtree of Orig tree: true

Pseudocode:

Traverse Binary Tree T1 in via In-order traversal and store the result in a String. Traverse Binary Tree T2 via In-order traversal and store the result in a String.
If In-order traversal of t2 is not a substring of In-order traversal of t2, return false.
Traverse Binary Tree T1 in via Pre-order traversal and store the result in a String. Traverse Binary Tree T2 via Pre-order traversal and store the result in a String.
If Pre-order traversal of t2 is not a substring of Pre-order traversal of t2, return false.
If In-order and Pre-Order Traversals of t2 are substrings of In-order and Pre-Order Traversals of t1, return true.


Code:

public class BinTreeCheckSubtree
{
private StringBuilder traversal;

public boolean isSubtree(BinTreeNode root1, BinTreeNode root2) {
	traversal=new StringBuilder();
	inOrderRecursive(root1);
	String tree1InOrder=traversal.toString();
	System.out.println("Orig tree inOrder"+tree1InOrder);
	
	
	traversal=new StringBuilder();
	inOrderRecursive(root2);
	String tree2InOrder=traversal.toString();
	System.out.println("toCheck tree inOrder"+tree2InOrder);
	if (tree1InOrder.indexOf(tree2InOrder)==-1) {return false;}
	
	traversal=new StringBuilder();
	preOrderRecursive(root1);
	String tree1PreOrder=traversal.toString();
	System.out.println("Orig tree preOrder"+tree1PreOrder);
	traversal=new StringBuilder();
	preOrderRecursive(root2);
	String tree2PreOrder=traversal.toString();
	System.out.println("toCheck tree preOrder"+tree2PreOrder);
	if (tree1PreOrder.indexOf(tree2PreOrder)==-1) {return false;}
	return true;
}

public void inOrderRecursive(BinTreeNode parent){
	if (parent==null) {return;}
	inOrderRecursive(parent.getLeftChild());
	traversal.append(parent.getNodeData()).append(",");
	inOrderRecursive(parent.getRightChild());
}

public void preOrderRecursive(BinTreeNode parent){
	if (parent==null) {return;}
	traversal.append(parent.getNodeData()).append(",");
	preOrderRecursive(parent.getLeftChild());
	preOrderRecursive(parent.getRightChild());
}
}

Click here to download and run code and test cases !