传送门
nowcoder
leetcode
题目描述
输入两棵二叉树A,B,判断 B 是不是 A 的子结构。
(ps:我们约定空树不是任意一个树的子结构)
C++ 代码 - nowcoder
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
class Solution { public: bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { if (pRoot1 == nullptr || pRoot2 == nullptr) return false;
return isSame(pRoot1, pRoot2) || HasSubtree(pRoot1->left, pRoot2) || HasSubtree(pRoot1->right, pRoot2); }
bool isSame(TreeNode* node1, TreeNode* node2) { if (node2 == nullptr) return true; if (node1 == nullptr || node1->val != node2->val) return false; return isSame(node1->left, node2->left) && isSame(node1->right, node2->right); } };
|
C++ 代码 - leetcode
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
class Solution { public: bool isSubStructure(TreeNode* A, TreeNode* B) { if (!A || !B) return false;
return isSame(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B); }
bool isSame(TreeNode* A, TreeNode* B) { if (!B) return true; if (!A || A->val != B->val) return false;
return isSame(A->left, B->left) && isSame(A->right, B->right); } };
|