Categories
Binary Tree Leetcode Recursion

Is Subtree

let isSubtree = function(mainTree, subTree) {

function isSame(left, right) {
if (left === right) return true;
if (left === null && right !== null) return false;
if (left !== null && right === null) return false;
if (left.val !== right.val) return false;
return isSame(left.left, right.left)
&& isSame(left.right, right.right);
}

if (mainTree === subTree) return true;
if (!mainTree) return false;
if (isSame(mainTree, subTree)) return true;

return isSubtree(mainTree.left, subTree) || isSubtree(mainTree.right, subTree);
};

Leave a Reply

Your email address will not be published. Required fields are marked *