输入两棵二叉树A和B,判断B是不是A的子结构。(空树不是任意一个树的子结构)
B是A的子结构, 即 A中有出现和B相同的结构和节点值。
例如:
给定的树 A:
3
/ \
4 5
/ \
1 2
给定的树 B:
4
/
1
返回 true,因为 B 与 A 的一个子树拥有相同的结构和节点值。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasSubTree(TreeNode* A, TreeNode* B) {
//B树节点为空,则返回true
if (B == NULL) {
return true;
}
//B树节点不为空,但是A树为空,则返回false
if (A == NULL) {
return false;
}
//A与B值不相等,则返回false
if (A->val != B->val) {
return false;
}
//A与B值相等,则继续比较左右节点
return hasSubTree(A->left, B->left) && hasSubTree(A->right, B->right);
}
bool isSubStructure(TreeNode* A, TreeNode* B) {
bool res = false;
if(A != NULL && B != NULL) {
if (A->val == B->val) {
//子树比较
res = hasSubTree(A, B);
}
if(!res) {
res = isSubStructure(A->left, B);
}
if (!res) {
res = isSubStructure(A->right, B);
}
}
return res;
}
};