Skip to content

Instantly share code, notes, and snippets.

@StevenXL
Created March 17, 2020 12:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save StevenXL/5df0431f1e5f02824d598a0c288408da to your computer and use it in GitHub Desktop.
Save StevenXL/5df0431f1e5f02824d598a0c288408da to your computer and use it in GitHub Desktop.
Subtree of Another Tree
function isSubtree(s, t) {
const queue = [s];
while (queue.length > 0) {
const node = queue.shift();
if (isSame(node, t)) {
return true;
} else {
if (node.left) {
queue.push(node.left);
}
if (node.right) {
queue.push(node.right);
}
}
}
return false;
}
function isSame(l, r) {
if (!l && !r) {
return true;
} else if (l && r) {
const lVal = l.val;
const rVal = r.val;
return lVal === rVal && isSame(l.left, r.left) && isSame(l.right, r.right);
} else {
return false;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment