[LeetCode][572] Subtree of Another Tree题解

版权声明:请注明转载地址 https://blog.csdn.net/OCEANtroye https://blog.csdn.net/OCEANtroye/article/details/83592973

[LeetCode][572] Subtree of Another Tree题解


题意:给一个树t和s,判断在t中是否有一个子树s。
思路:

dfs遍历一个树把t和s的val值一样的节点加入treenode*型的vector中,再使用搜索判断这个节点x开始,x和s是否一模一样,这里使用dfs来写isSame


代码

/*
 * [572] Subtree of Another Tree
 *
 * https://leetcode.com/problems/subtree-of-another-tree/description/
 *
 * algorithms
 * Easy (40.42%)
 * Total Accepted:    70.4K
 * Total Submissions: 174.1K
 * Testcase Example:  '[3,4,5,1,2]\n[4,1,2]'
 *
 *
 * 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.
 *
 */
/**
 * 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
{
  private:
    vector<TreeNode *> res;

  public:
    bool isSubtree(TreeNode *s, TreeNode *t)
    {
        dfs(s, t);
        for (int i = 0; i < res.size(); i++)
        {
            if (isSame(t, res[i]))
            {
                return true;
            }
        }
        return false;
    }
    bool isSame(TreeNode *a, TreeNode *b)
    {
        if (a == nullptr && b == nullptr)
        {
            return true;
        }
        else if ((a == nullptr && b) || (a && b == nullptr))
        {
            return false;
        }
        else if (a->val == b->val)
        {
            return isSame(a->left, b->left) && isSame(a->right, b->right);
        }
        return false;
    }
    void dfs(TreeNode *s, TreeNode *t)
    {
        if (s)
        {
            if (s->val == t->val)
            {
                res.push_back(s);
            }
            if (s->left)
            {
                dfs(s->left, t);
            }
            if (s->right)
            {
                dfs(s->right, t);
            }
        }
    }
};


提交结果:

√ Accepted
√ 176/176 cases passed (16 ms)
√ Your runtime beats 56.2 % of cpp submissions

猜你喜欢

转载自blog.csdn.net/OCEANtroye/article/details/83592973