-
-
Save StevenXL/5df0431f1e5f02824d598a0c288408da to your computer and use it in GitHub Desktop.
Subtree of Another Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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