How to check if a tree is a subtree of another

🚀 Day 122 of #LeetCode Challenge! Problem: Subtree of Another Tree 💡 My Approach: The goal is to check whether one tree (subRoot) is a subtree of another (root). Here’s how I approached it: Traverse the main tree (root) recursively. At each node, check if the subtree starting there is identical to subRoot. If not, keep checking in the left and right subtrees. For the comparison, a helper function isSameTree() ensures both trees have identical structure and node values. 🧠 Key Idea A tree subRoot is a subtree of root if there exists a node in root such that the subtree rooted at that node is structurally identical to subRoot. ✨ Example Input: root = [3,4,5,1,2] subRoot = [4,1,2] Output: ✅ true Explanation: The subtree starting at node 4 in root matches subRoot. ⏱ Complexity TypeValueTimeO(M × N) — for each node in root, we may compare with all nodes in subRootSpaceO(H) — recursion stack (H = height of the tree) 📎 GitHub Link: https://lnkd.in/gv3w8RFe #LeetCode #BinaryTree #Recursion #C++ #ProblemSolving #Day122 #CodingChallenge

  • text

To view or add a comment, sign in

Explore content categories