Skip to content

Commit 50ea491

Browse files
Is subtree of another tree
1 parent 85325d3 commit 50ea491

File tree

2 files changed

+58
-1
lines changed

2 files changed

+58
-1
lines changed

src/main/java/dsa/trees/BinaryTree.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ private void populate(Scanner scanner, Node node) {
8080

8181
public Node buildPreOrderTree(int[] nodes) {
8282
idx++;
83-
if (nodes[idx] == -1) {
83+
if (nodes.length <= idx || nodes[idx] == -1) {
8484
return null;
8585
}
8686
Node newNode = new Node(nodes[idx]);
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
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

Comments
 (0)