1+ package leetcode .easy ;
2+
3+ import dsa .trees .BinarySearchTreeTraversal ;
4+ import dsa .trees .BinaryTree ;
5+
6+ /**
7+ * https://leetcode.com/problems/subtree-of-another-tree/description/
8+ * <p>
9+ * Example 1:
10+ * Input: root = [3,4,5,1,2], subRoot = [4,1,2]
11+ * Output: true
12+ * <p>
13+ * Example 2:
14+ * Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
15+ * Output: false
16+ */
17+ class SubtreeOfAnotherTree {
18+
19+ public static void main (String [] args ) {
20+ BinarySearchTreeTraversal binarySearchTreeTraversal = new BinarySearchTreeTraversal ();
21+
22+ int [] rootElements = {3 , 4 , 5 , 1 , 2 };
23+ int [] subRootElements = {4 , 1 , 2 };
24+
25+ BinaryTree .Node rootNode = binarySearchTreeTraversal .buildPreOrderTree (rootElements );
26+ BinaryTree .Node subRootNode = binarySearchTreeTraversal .buildPreOrderTree (subRootElements );
27+
28+ System .out .println ("Is subtree of another tree " + isSubtree (rootNode , subRootNode ));//Output: true
29+ }
30+
31+ public static boolean isSubtree (BinaryTree .Node root , BinaryTree .Node subRoot ) {
32+ if (subRoot == null ) {
33+ return true ;
34+ }
35+ if (root == null ) {
36+ return false ;
37+ }
38+ if (isIdentical (root , subRoot )) {
39+ return true ;
40+ }
41+ return isSubtree (root .getLeft (), subRoot ) || isSubtree (root .getRight (), subRoot );
42+ }
43+
44+ public static boolean isIdentical (BinaryTree .Node root , BinaryTree .Node subRoot ) {
45+ if (subRoot == null && root == null ) {
46+ return true ;
47+ }
48+ if (root == null || subRoot == null ) {
49+ return false ;
50+ }
51+ if (root .getValue () == subRoot .getValue ()) {
52+ return isIdentical (root .getLeft (), subRoot .getLeft ()) && isIdentical (root .getRight (), subRoot .getRight ());
53+ }
54+ return false ;
55+ }
56+
57+ }
0 commit comments