Subtree of Another Tree

406 篇文章 0 订阅
406 篇文章 0 订阅

1,题目要求

Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node’s descendants. The tree s could also be considered as a subtree of itself.

给定两个非空的二进制树s和t,检查树t是否具有完全相同的结构和具有子树s的节点值。 s的子树是一个树,由s中的节点和所有节点的后代组成。 树也可以被视为自己的子树。

在这里插入图片描述

2,题目思路

这道题,是给定两棵树s和t,判断t是否是s的子树。

还是使用了递归手法,判断两棵树是否相等

  • 如果两个节点都为空,说明二者相同;
  • 如果一个为空而另一个不为空、或者二者值不同,说明这两个树不等;
  • 依次对两棵树中的节点判断,即可得到结果。

其中,我们需要对树s中的每个节点都作为根节点进行递归判断才行。

3,代码实现

1,层次遍历s中所有节点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if(s == nullptr)
            return false;
        queue<TreeNode*> q;
        q.push(s);
        while(q.empty() == false){
            TreeNode* node = q.front();
            q.pop();
            if(isSame(node, t))
                return true;
            if(node->left)
                q.push(node->left);
            if(node->right)
                q.push(node->right);
        }
        return false;
        
    }
    
private:
    bool isSame(TreeNode* ss, TreeNode* tt){
        if(ss == nullptr && tt == nullptr)
            return true;
        
        if(ss == nullptr || tt == nullptr ||
          ss->val != tt->val)
            return false;
        
        return isSame(ss->left, tt->left) && isSame(ss->right, tt->right);
    }
};

2,递归遍历s中所有节点

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
int x = []() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    return 0;
}();

class Solution {
public:
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if(s == nullptr)
            return false;
        if(isSame(s, t)
        	return true;
        return (isSubtree(s->left, t) || isSubtree(s->right, t);
        
    }
    
private:
    bool isSame(TreeNode* ss, TreeNode* tt){
        if(ss == nullptr && tt == nullptr)
            return true;
        
        if(ss == nullptr || tt == nullptr ||
          ss->val != tt->val)
            return false;
        
        return isSame(ss->left, tt->left) && isSame(ss->right, tt->right);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值