剑指offer---树的子结构
题目:树的子结构
要求:输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)
/* struct TreeNode { int val; struct TreeNode *left; struct TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) { } };*/ class Solution { public: bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { } };
解题代码:
1 class Solution { 2 public: 3 bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { 4 bool res = false; 5 6 if(pRoot1 != nullptr && pRoot2 != nullptr){ 7 //在Tree1中找到对应Tree2的根节点的节点 8 if(pRoot1->val == pRoot2->val) 9 //以这个根节点为为起点判断是否包含Tree2 10 res = doesTree1HaveTree2(pRoot1, pRoot2); 11 //未不到,以root的左孩子当作起点,判断是否包含Tree2 12 if(!res) 13 res = HasSubtree(pRoot1->left, pRoot2); 14 //未不到,以root的右孩子当作起点,判断是否包含Tree2 15 if(!res) 16 res = HasSubtree(pRoot1->right, pRoot2); 17 } 18 return res; 19 } 20 21 private: 22 bool doesTree1HaveTree2(TreeNode* pRoot1, TreeNode* pRoot2){ 23 //如果Tree2已经遍历完了都能对应的上,返回true 24 if(pRoot2 == nullptr) 25 return true; 26 //如果Tree2还没有遍历完,Tree1遍历完,返回false 27 if(pRoot1 == nullptr) 28 return false; 29 //值不相等,返回false 30 if(pRoot1->val != pRoot2->val) 31 return false; 32 //如果根节点对应的上,那么就分别去子节点里面匹配 33 return doesTree1HaveTree2(pRoot1->left, pRoot2->left) && doesTree1HaveTree2(pRoot1->right, pRoot2->right); 34 } 35 };