LeetCode 572: Subtree of Another Tree Solution

Master LeetCode problem 572 (Subtree of Another Tree), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

Problem Explanation

Explanation

To solve this problem, we can recursively traverse the main tree and check if at any node, a subtree exists that is identical to the given subRoot tree. We can do this by comparing the trees starting from the current node. We can break down the problem into smaller sub-problems by recursively checking if the left or right subtree of the current node is equal to the subRoot tree.

Time complexity: O(m*n) where m is the number of nodes in the main tree and n is the number of nodes in the subRoot tree.
Space complexity: O(min(m,n))

Solution Code

class Solution {
    public boolean isSubtree(TreeNode root, TreeNode subRoot) {
        if (root == null) return false;
        return isSameTree(root, subRoot) || isSubtree(root.left, subRoot) || isSubtree(root.right, subRoot);
    }
    
    private boolean isSameTree(TreeNode p, TreeNode q) {
        if (p == null && q == null) return true;
        if (p == null || q == null) return false;
        return p.val == q.val && isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 572 (Subtree of Another Tree)?

This page provides optimized solutions for LeetCode problem 572 (Subtree of Another Tree) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 572 (Subtree of Another Tree)?

The time complexity for LeetCode 572 (Subtree of Another Tree) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 572 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 572 in Java, C++, or Python.

Back to LeetCode Solutions