题意:输入两棵二叉树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 judge(TreeNode* pRoot1, TreeNode* pRoot2){ if(pRoot1 == NULL && pRoot2 == NULL) return true; if(pRoot1 == NULL) return false; if(pRoot2 == NULL) return true; if(pRoot1 -> val != pRoot2 -> val) return false; return judge(pRoot1 -> left, pRoot2 -> left) && judge(pRoot1 -> right, pRoot2 -> right); } bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { if(pRoot1 == NULL) return false; if(pRoot2 == NULL) return false; if(pRoot1 -> val == pRoot2 -> val){ if(judge(pRoot1, pRoot2)) return true; } return HasSubtree(pRoot1 -> left, pRoot2) || HasSubtree(pRoot1 -> right, pRoot2); } };
题意:判断B是否为A的子树。
class Solution { public: bool judge(TreeNode* pRoot1, TreeNode* pRoot2){ if(pRoot1 == NULL && pRoot2 == NULL) return true; if(pRoot1 == NULL) return false; if(pRoot2 == NULL) return false; if(pRoot1 -> val != pRoot2 -> val) return false; return judge(pRoot1 -> left, pRoot2 -> left) && judge(pRoot1 -> right, pRoot2 -> right); } bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2) { if(pRoot1 == NULL) return false; if(pRoot2 == NULL) return false; if(pRoot1 -> val == pRoot2 -> val){ if(judge(pRoot1, pRoot2)) return true; } return HasSubtree(pRoot1 -> left, pRoot2) || HasSubtree(pRoot1 -> right, pRoot2); } };