标签:div 参考 result content bool 存在 描述 min color
时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
/* 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) { bool result = false; if(pRoot1 != NULL && pRoot2 != NULL) { if(pRoot1->val == pRoot2->val) { //该根节点作为起点判断是否包含pRoot2 result = judgeSubTree(pRoot1,pRoot2); } //如果没有找到,就去该节点的左子树中找 if(!result) { result = HasSubtree(pRoot1->left,pRoot2); } //如果还没有找到,就去该节点的右子树中找 if(!result) { result = HasSubtree(pRoot1->right,pRoot2); } } return result; } private: bool judgeSubTree(TreeNode *node1,TreeNode *node2) { if(node2 == NULL) return true; if(node1 == NULL) return false; if(node1->val != node2->val) { return false; } return judgeSubTree(node1->left,node2->left) && judgeSubTree(node1->right,node2->right); } };
在judgeSubTree函数中对node1->val 与node2->val判断是否相等是有必要的,应为该函数是一个递归函数,下面递归调用的时候,还是要判断传进去的两个节点的值是否相等
另一种写法:
/* 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) { if(pRoot1 == NULL || pRoot2 == NULL) { return false; } return judeSubTree(pRoot1,pRoot2) || judeSubTree(pRoot1->left,pRoot2) ||judeSubTree(pRoot1->right,pRoot2); } bool judeSubTree(TreeNode* node1,TreeNode * node2) { if(node2 == NULL) return true; if(node1 == NULL) return false; if(node1->val != node2->val) return judeSubTree(node1->left,node2) || judeSubTree(node1->right,node2); return judeSubTree(node1->left,node2->left)&& judeSubTree(node1->right,node2->right); } };
子结构包含与子树,子树会要求更加严格,不仅结构相同,节点的值也要相同,只需要对其值判断相等,不能就直接返回false即可
判断是否为子树:
/* 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) { if(pRoot1 == NULL || pRoot2 == NULL) { return false; } return judeSubTree(pRoot1,pRoot2) || judeSubTree(pRoot1->left,pRoot2) ||judeSubTree(pRoot1->right,pRoot2); } bool judeSubTree(TreeNode* node1,TreeNode * node2) { if(node2 == NULL) return true; if(node1 == NULL) return false; if(node1->val != node2->val) return false; return judeSubTree(node1->left,node2->left)&& judeSubTree(node1->right,node2->right); } };
标签:div 参考 result content bool 存在 描述 min color
原文地址:https://www.cnblogs.com/whiteBear/p/12523524.html