C++:
/**
* 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 checkSubTree(TreeNode* t1, TreeNode* t2) {
if ( !t1 || !t2 ) {
return false;
}
if ( t1 -> val == t2 -> val ) {
return checkEqual( t1, t2 );
} else {
if ( t1 -> left && checkSubTree( t1 -> left, t2 ) ) {
return true;
}
if ( t1 -> right && checkSubTree( t1 -> right, t2 ) ) {
return true;
}
return false;
}
}
bool checkEqual(TreeNode* t1, TreeNode* t2) {
if ( !t1 && !t2 ) {
return true;
}
if ( !t1 || !t2 ) {
return false;
}
return t1 -> val == t2 -> val && checkEqual( t1 -> left, t2 -> left ) && checkEqual( t1 -> right, t2 -> right );
}
};
网友评论