zoukankan      html  css  js  c++  java
  • LC 572. Subtree of Another Tree

    link

    /**
     * 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> spre,tpre;
    
        bool isSubtree(TreeNode* s, TreeNode* t) {
            preorder(s,spre);
            preorder(t,tpre);
    
            vector<int> table(tpre.size());
            int len=0;
            for(int i=1;i<tpre.size();i++){
                if(tpre[i]==tpre[len]){
                    len++;
                    table[i]=len;
                }else{
                    if(len==0) {
                        table[i]=0;
                    }else{
                        len=table[len-1];
                        i--;
                    }
                }
            }
            int i=0;
            int j=0;
            while(i<spre.size()){
                if(spre[i]==tpre[j]){
                    i++;
                    j++;
                    if(j==tpre.size()) return true;
                }else{
                    if(j==0){
                        i++;
                    }else{
                        j=table[j-1];
                    }
                }
            }
            return false;
        }
    
        void preorder(TreeNode* t, vector<int>& vs){
            if(t==nullptr) return;
            vs.push_back(t->val);
            if(t->left) preorder(t->left,vs);
            else vs.push_back(INT_MIN);
            if(t->right) preorder(t->right,vs);
            else vs.push_back(INT_MAX);
        }
    };
  • 相关阅读:
    穷举和迭代
    for循环练习题
    case when then else end 用法
    如何将数据库账号(用户)解锁
    比赛安排
    How to spend you day ?
    异常-问题型
    重载和重写的区别
    new关键字的理解-问题型
    源辰项目-1
  • 原文地址:https://www.cnblogs.com/FEIIEF/p/12840692.html
Copyright © 2011-2022 走看看