标签:bool iss node bsp lse nod == sub ||
题目:
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)。
解答:
1 class Solution { 2 bool isSubtree(TreeNode* pRootA, TreeNode* pRootB) 3 { 4 if (pRootB == NULL) 5 { 6 return true; 7 } 8 if (pRootA == NULL) 9 { 10 return false; 11 } 12 if (pRootB->val == pRootA->val) 13 { 14 return isSubtree(pRootA->left, pRootB->left) 15 && isSubtree(pRootA->right, pRootB->right); 16 } 17 else 18 { 19 return false; 20 } 21 } 22 public: 23 bool HasSubtree(TreeNode* pRootA, TreeNode* pRootB) 24 { 25 if (pRootA == NULL || pRootB == NULL) 26 { 27 return false; 28 } 29 return isSubtree(pRootA, pRootB) || 30 HasSubtree(pRootA->left, pRootB) || 31 HasSubtree(pRootA->right, pRootB); 32 } 33 };
标签:bool iss node bsp lse nod == sub ||
原文地址:https://www.cnblogs.com/ocpc/p/12838178.html