---
# System prepended metadata

title: (Easy) 572. Subtree of Another Tree
tags: [leetcode]

---

# (Easy) 572. Subtree of Another Tree
## Run Code
![](https://i.imgur.com/zUjxx6r.png)

## 題意
是否能從root的tree中找到subtree。
## 解題思路
在isSubtree中先找到subRoot的第一個value是否有在root中，接著在findSubRoot中判斷是否接下來的children都一樣。
## 困難之處
要從他給的function來return answer，好喔。
## Code
```cpp=
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    bool isSubtree(TreeNode* root, TreeNode* subRoot) {
        if(root==NULL) return false;
        return findSubRoot(root,subRoot) || 
        isSubtree(root->left, subRoot) || 
        isSubtree(root->right, subRoot);
    }
    bool findSubRoot(TreeNode* root, TreeNode* subRoot){
        //compare 
        if(root==NULL && subRoot==NULL) return true;
        if(root==NULL || subRoot==NULL || root->val!=subRoot->val) return false;
        //left child by recursive //right child by recursive
        return findSubRoot(root->left, subRoot->left) && findSubRoot(root->right, subRoot->right);
    }
};
```
###### tags: `leetcode`