Skip to content

ยท 1 min read

Blind 75 - Subtree of Another Tree

Check if root is same as subtree or root.left is same or root.right is same;

[Video]

Check if one tree is a subtree of another.

Link

Approaches

O(n*2) time; O(1) space; 12 lines

Check if root is same as subtree or root.left is same or root.right is same;

Half the solution is from Same Tree

    public boolean isSame(TreeNode one, TreeNode two){
        if(one == null && two == null){
            return true;
        }
        if(one == null || two == null){
            return false;
        }
        return one.val == two.val && isSame(one.left, two.left) && isSame(one.right, two.right);
    }
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if(root == null){
            return false;
        }
        if(isSame(root, subRoot)){
            return true;
        }
        return isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }

Get new posts by email

No spam. Unsubscribe anytime. Or grab the RSS feed.

Mailto-based for now. ButtonDown / ConvertKit can replace this form later.


Comments lazy-load on scroll. Prefer GitHub? Giscus activates once PUBLIC_GISCUS_* env vars are set (see Giscus.astro).

Index

Index

Back to Blog