572. Subtree of Another Tree(Easy)

原题目:
  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中的一个节点及其所有子节点组成,s也可以是自己本身的一个子树。

代码如下:

/**
 * 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) {
        //s为空树,或者当s等于NULL时还没找到相等的一个节点,返回false
        if(s == NULL) return false ;
        //找到一个相等节点,如果这个节点以下全都于t相等,返回true
        if(s->val == t->val && isTheSame(s , t)) return true ;
        //否则继续往下寻找是否邮箱等节点,左右子树任意一个找到即可
        else return isSubtree(s->left , t) || isSubtree(s->right , t) ;
        return false ;
    }

    bool isTheSame(TreeNode* s, TreeNode* t){
        //两个数同时到达底端,说明完全相等
        if(s == NULL && t == NULL) return true ;
        //当其中有个已到达底端但另一个还没有,返回false
        if((s != NULL && t == NULL) || (s == NULL && t != NULL)) return false ;
        //当前val相等,继续对左子树右子树做同样的事,如果都true,则返回true
        if(s->val == t->val && isTheSame(s->left , t->left) && isTheSame(s->right , t->right)) 
            return true ;
        return false ;
    }
};

主要是对树的递归处理还不熟悉,以此题为提醒。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值