Leetcode#572. 另一个树的子树,C++实现

目录

  • 1. 题目
  • 2. 方法一
    • 2.1. 代码
    • 2.2. 结果

1. 题目

Leetcode#572. 另一个树的子树,C++实现_第1张图片

2. 方法一

2.1. 代码

class Solution {
public:
    bool isSubtree(TreeNode* s, TreeNode* t) {
        if(t==NULL) return true;
        if(s==NULL) return false;
        return isSubtreewithroot(s,t)||isSubtree(s->left,t)||isSubtree(s->right,t);
    }
    bool isSubtreewithroot(TreeNode* s, TreeNode* t)
    {
       if(s==NULL&&t==NULL) return true;
        if(s==NULL||t==NULL) return false;

        if(t->val!=s->val) return false;
        else return isSubtreewithroot(s->left,t->left)&&isSubtreewithroot(s->right,t->right);
    }
};

2.2. 结果

Leetcode#572. 另一个树的子树,C++实现_第2张图片

你可能感兴趣的:(数据结构与算法)