另一棵树的子树
双层递归
第一层前序遍历找点
第二层对比这个点和另一个子树是否相同
/** * 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 compare(TreeNode* cur, TreeNode* subRoot) { if(cur==nullptr && subRoot==nullptr) return true; else if(cur == nullptr && subRoot != nullptr) return false; else if(cur != nullptr && subRoot == nullptr) return false; if(cur->val != subRoot->val) return false; bool left_val = compare(cur->left,subRoot->left); bool right_val = compare(cur->right,subRoot->right); return left_val&right_val; } //第一层前序遍历看点 void traversal(TreeNode* cur, TreeNode* subRoot , bool &val) { if(cur==nullptr) return; bool mid_val = compare(cur,subRoot);//调用第二层递归 //cout<<mid_val<<endl; val = val | mid_val ; traversal(cur->left , subRoot ,val); traversal(cur->right , subRoot ,val); } bool isSubtree(TreeNode* root, TreeNode* subRoot) { bool val = false; traversal(root,subRoot,val); return val; } };