剑指offer----树的子结构

题目描述
输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)。

//判断 b是否是a的子结构,已经排除了空树不是任意一个树的子结构的情况下。
    bool is_value(TreeNode* a,TreeNode* b)
    {
        if(a==NULL&&b==NULL)return true;//都为空则是子结构
        if(b==NULL)return true;//b为空,a不管为什么b都是a的子结构
        if(a==NULL)return false;//当a为空是,b不为空是,必然不是子结构
        if(a->val!=b->val)return false;
        else{
            return is_value(a->left,b->left)&&is_value(a->right,b->right);
        }
    }
    //非递归中序遍历
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if(pRoot2==NULL||pRoot1==NULL)return false;
        stack<TreeNode*> s;
        TreeNode* cur=pRoot1;
        while(s.empty()!=true||cur!=NULL)
        {
            while(cur)
            {
                s.push(cur);
                cur=cur->left;
            }
            if(s.empty()==true) break;
            if(is_value(s.top(),pRoot2)==true) return true;
            cur=(s.top())->right;
            s.pop();
        }
        return false;
    }

猜你喜欢

转载自blog.csdn.net/xiaocongcxc/article/details/82393165