[LeetCode] Subtree of Another Tree

题目链接:点击打开链接

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.

Example 1:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
Given tree t:
   4 
  / \
 1   2
Return  true , because t has the same structure and node values with a subtree of s.

Example 2:
Given tree s:

     3
    / \
   4   5
  / \
 1   2
    /
   0
Given tree t:
   4
  / \
 1   2

Return false.


不得不说关于树的操作我真的太不熟悉了,以至于读完题目我都没什么想法。一般关于树的遍历必定是递归,所以我就先撸了一个递归遍历s树中的子树,对于每一棵子树都跟t树递归比较。整理了一下递归函数就可以运行了。试探性地交一发,居然没有TLE,还超过了78.67%的提交......


果然不能把LeetCode当成ACM来打= =

代码如下:

/**
 * 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 cmp(TreeNode* s, TreeNode* t)
    {
        if(s==NULL&&t==NULL)return true;
        if(s==NULL||t==NULL)return false;
        if(s->val==t->val)
        {
            return cmp(s->left,t->left)&&cmp(s->right,t->right);
        }
        else return false;
    }
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if(s==NULL&&t==NULL)return true;
        if(s==NULL||t==NULL)return false;
        if(cmp(s,t))return true;
        else return isSubtree(s->left,t)||isSubtree(s->right,t);
    }
};


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值