JZ17 树的子结构
本文最后更新于:2022年4月9日 中午
Solution
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
|
class Solution { public: bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { if (!pRoot1 || !pRoot2) return false; return travel(pRoot1, pRoot2) || HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2); } bool travel(TreeNode* root1, TreeNode* root2) { if (root2 == nullptr) return true; if (root1 == nullptr) return false;
return root1->val == root2->val && travel(root1->left, root2->left) && travel(root1->right, root2->right); } };
|