leetcode572.另一个树的子树

题目链接:https://leetcode-cn.com/problems/subtree-of-another-tree/

思路:dfs序+暴力匹配

  1. 错误的想法:直接把 ss 和 tt 先转换成 DFS 序,然后看 tt 的 DFS 序是否是 ss 的 DFS 序的「子串」。 反例如下:

1588822106079

  1. 为了解决这个问题,我们可以引入两个空值 lNull 和 rNull,当一个节点的左孩子或者右孩子为空的时候,就插入这两个空值,这样 DFS 序列就唯一对应一棵树。处理完之后,就可以通过判断 「ss 的 DFS 序包含 tt 的 DFS 序」来判断答案。
/**
 * 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:
    vector<int>v;
    void LDR(TreeNode* s)
    {
        if(s->left==NULL)
            v.push_back(-1);
        else
            LDR(s->left);
        v.push_back(s->val);
        if(s->right==NULL)
            v.push_back(-2);
        else
            LDR(s->right);
    }
    vector<int>v1;
    void LDR1(TreeNode* s)
    {
        if(s->left==NULL)
            v1.push_back(-1);
        else
            LDR1(s->left);
        v1.push_back(s->val);
        if(s->right==NULL)
            v1.push_back(-2);
        else
            LDR1(s->right);
    }

    bool isSubtree(TreeNode* s, TreeNode* t) {
        LDR(s);
        LDR1(t);
        int i=0;
        int j=0;
        int index=0;
        int flag=0;
        while(true)
        {   
            if(j==v1.size())
            {
                flag=1;
                break;
            }
            if(index==v.size()-v1.size()+1)
            {
                break;
            }
            if(v[i]==v1[j])
            {
                i++;
                j++;
            }
            else
            {
                i=index+1;
                index++;
                j=0;
            }
        }
        if(flag==1)
        {
            return true;
        }
        return false;
    }
};
posted @ 2020-05-07 11:53  火车不是推的  阅读(95)  评论(0编辑  收藏  举报