0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Leetcode Easy 572. Subtree of Another Tree

Posted at

2つの木構造S,Tを比較する。
SのNodeを一つずつ走査し、Tと比較する。

つまり2回再帰(深さ優先探索)を使って走査する。
ーRootとなるSを一つずつ走査する
ーそのSのRootとTのRootを順に比較する

class Solution {
public:
    bool check(TreeNode* s, TreeNode* t) {
        if (s == NULL && t == NULL) {
            return true;
        }
        else if (s == NULL && t != NULL) {
            return false;
        }
        else if (s != NULL && t == NULL) {
            return false;
        }

        if (t->val != s->val) {
            return false;
        }

        return check(s->left, t->left) && check(s->right, t->right);
    }

    bool S_Scan(TreeNode* s, TreeNode* t) {
        if (s == NULL)return false;

        if (s->val == t->val) {
            if (check(s, t)) {
                return true;
            }
        }

        return S_Scan(s->left, t) || S_Scan(s->right, t);
        
    }

    bool isSubtree(TreeNode* s, TreeNode* t) {
        if (t == NULL) return false;
        if (s == NULL) return false;

        return S_Scan(s, t);
    }
};
//    TreeNode* s = new TreeNode(1);
//    s->left = new TreeNode(NULL);
//    s->right = new TreeNode(1);
//    s->right->left = new TreeNode(NULL);
//    s->right->right = new TreeNode(2);
//
//    TreeNode* t = new TreeNode(1);
//    t->left = new TreeNode(NULL);
//    t->right = new TreeNode(2);
//
//
//    cout << Sol->isSubtree(s,t);
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?