LeetCode刷题 | 572. Subtree of Another Tree

来源:互联网 发布:js display none 显示 编辑:程序博客网 时间:2024/06/06 13:16

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

解题思路:

这题要求给定两棵树s和t,如果t是s的子树那么返回true否则返回false,我的思路是这样,使用广度优先遍历s的每一个点,如果发现s中某个节点a的值和t的根节点的值相同,那么检测以a为根节点的子树和树t是否完全相同,如果完全相同则返回true,否者继续广度遍历s

广度遍历s使用头文件include<queue>实现,检测以a为根节点子树和t是否完全相同使用的是深度优先遍历


class Solution {

#include<queue>

    public:

    bool isSubtree(TreeNode* s, TreeNode* t) {

        queue<TreeNode *> Q;

        Q.push(s);

        while(!Q.empty())

        {

            TreeNode * o=Q.front(); Q.pop();

            if(o==NULL) continue;

            Q.push(o->left);Q.push(o->right);

            if(o->val==t->val) if(p(o,t))return true; 

        }

        return false;

       

    }

   

    bool p(TreeNode *s,TreeNode * t)

    {

        if(s==NULL&&t==NULL) returntrue;

        else if(s==NULL||t==NULL) return false;

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

        else

        {

           if(p(s->left,t->left)&&p(s->right,t->right))

                return true;

            else return false;

        }

    }

};

这题还有一个更好的方法就是只比较s中最大深度与t相同的子树与t,比较他们是否相同,这样效率能提升很多倍