在树的遍历中,时刻警惕每一处需要访问的有没有可能是NULL,如果NULL怎么处理
判断指针是不是NULL既能避免访问空指针而造成程序崩溃,同时也经常能设置递归的退出条件
接着先审题
给定两个非空二叉树 s 和 t,检验 s 中是否包含和 t 具有相同结构和节点值的子树。s 的一个子树包括 s 的一个节点和这个节点的所有子孙。s 也可以看做它自身的一棵子树。
示例 1:
给定的树 s:
3
/ \
4 5
/ \
1 2
给定的树 t:
4
/ \
1 2
返回 true,因为 t 与 s 的一个子树拥有相同的结构和节点值。
示例 2:
给定的树 s:
3
/ \
4 5
/ \
1 2
/
0
给定的树 t:
4
/ \
1 2
返回 false。
解题思路:递归呗!!!
第一步:先在树s中查找和树t根节点相同的节点,查找递归!!!
第二步:判断两个节点的左右子树是否完全相同,递归!!!
讲不多说,上代码!!!
/**
* 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 isSubtree(TreeNode* s, TreeNode* t) {
return hasRootNode(s, t);
}
bool hasRootNode(TreeNode* s, TreeNode* t){
bool result = false;
if(s != NULL && t != NULL){
//其实本题中t!=NULL总是成立的,如果s==NULL那么在树s中没有找到和t根节点相同的值
if(s->val == t->val){
result = isSameTree(s, t);
}
if(!result)
result = hasRootNode(s->left, t);
if(!result)
result = hasRootNode(s->right, t);
}
return result;
}
bool isSameTree(TreeNode* s, TreeNode* t){
bool result = false;
if(s == NULL && t == NULL)
result = true;
else if(s == NULL || t == NULL){
result = false;
}
else if(s->val != t->val){
result = false;
}
else{
//result = isSameTree(s->left, t->left);
//先判断左子树再判断右子树,如果左子树不相同,那么右子树也没有必要再进行下一步判断了
//if(result){
// result = isSameTree(s->right, t->right);
//}
result = isSameTree(s->left, t->left) && isSameTree(s->right, t->right);
}
return result;
}
};
欢迎和评论和提出意见!!!
突然想到,如果只是判断树t是否在树s中出现,那么需要修改代码的哪些部分呢???
转载请注明链接,谢谢~