Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit a00df3e

Browse files
authored
Merge pull request knaxus#123 from abuasifkhan/abuasifkhan_adding_check-binary-tree-subtree-another-binary-tree
Adding Check if a binary tree is subtree of another binary tree
2 parents 43ed1bc + 0f596d8 commit a00df3e

File tree

1 file changed

+37
-0
lines changed
  • src/_DataStructures_/Trees/BinaryTree/check-binary-tree-subtree-another-binary-tree

1 file changed

+37
-0
lines changed
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
// Check if a binary tree is subtree of another binary tree
2+
// Root of the source tree and the tree to be matched are provided in the parameters.
3+
// Return true/false based on whether or not the given tree is the subtree of the source tree
4+
// Time complexity : O(m*n) m is the number of nodes of the original tree,
5+
// n is the number of nodes in the tree to be matched
6+
7+
function areIdentical(rootOfOriginalTree, rootOfMatchingTree) {
8+
if (rootOfOriginalTree === null && rootOfMatchingTree === null) {
9+
return true;
10+
}
11+
12+
if (rootOfOriginalTree === null || rootOfMatchingTree === null) {
13+
return false;
14+
}
15+
16+
return (rootOfOriginalTree.value === rootOfMatchingTree.value) && areIdentical(rootOfOriginalTree.leftChild, rootOfMatchingTree.leftChild) && areIdentical(rootOfOriginalTree.rightChild, rootOfMatchingTree.rightChild);
17+
}
18+
19+
function isSubtree(rootOfOriginalTree, rootOfMatchingTree) {
20+
if (rootOfMatchingTree === null) {
21+
return true;
22+
}
23+
24+
if (rootOfOriginalTree === null) {
25+
return false;
26+
}
27+
28+
if (areIdentical(rootOfOriginalTree, rootOfMatchingTree)) {
29+
return true;
30+
}
31+
32+
return isSubtree(rootOfOriginalTree.leftChild, rootOfMatchingTree) || isSubtree(rootOfMatchingTree.rightChild, rootOfMatchingTree);
33+
}
34+
35+
module.exports = {
36+
isSubtree,
37+
};

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /