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

本文介绍了一种算法,用于判断一棵二叉树是否为另一棵二叉树的子结构。通过递归的方式实现了该算法,并提供了二叉树的创建与遍历方法。

// test20.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<string>
#include<queue>
#include<stack>

using namespace std;



struct TreeNode {
    int val;
    struct TreeNode *left;
    struct TreeNode *right;
    TreeNode(int x) :
    val(x), left(NULL), right(NULL) {
    }
};
class Solution {
public:
    //1.先在二叉树tree1中找到tree2的根节点
    //2.在判断tree2的左右孩子是否在tree1中
    //3.如果不存在继续遍历tree1的左孩子和右孩子
    bool HasSubtree(TreeNode* pRoot1, TreeNode* pRoot2)
    {
        if (pRoot1 == NULL) return false;//这一点很重要,要不然if (pRoot1->val == pRoot2->val)会报空指针的错误
        if (pRoot2 == NULL) return false;

        bool result = false;
        if (pRoot1->val == pRoot2->val)
        {
            result = DoseTree1HasTree2(pRoot1,pRoot2);
        }
        if (result == false)
            result = HasSubtree(pRoot1->left,pRoot2);
        if (result == false)
            result = HasSubtree(pRoot1->right,pRoot2);
        return result;

    }

    //如果tree1为空,返回false;如果tree2为空,返回true;如果两者都不为空,继续判断其左右孩子
    bool DoseTree1HasTree2(TreeNode* tree1, TreeNode* tree2)
    {
        if (tree1 == NULL &&tree2 == NULL) return true;//tree1和tree2都为空
        else if (tree1 == NULL && tree2!=NULL) return false;
        else if (tree1 != NULL && tree2==NULL) return true;
        else 
        {
            if (tree1->val != tree2->val) return false;
            return DoseTree1HasTree2(tree1->left, tree2->left) && DoseTree1HasTree2(tree1->right, tree2->right);
        }
        
    }



    void preCreate(TreeNode* &T)
    {
        int num;
        cin >> num;
        if (num == 0) T = NULL;
        else
        {
            T = new TreeNode(num);
            preCreate(T->left);
            preCreate(T->right);
        }
    }

    void preOrder(TreeNode* T)
    {
        if (T == NULL) return; 
        else
        {
            cout << T->val << "  ";
            preOrder(T->left);
            preOrder(T->right);
        }
    }
};
int main()
{
    
    Solution so;
    TreeNode *T1;
    TreeNode *T2;
    vector<int> pre = { 1,2,4,7,3,5,6,8 };
    vector<int> in = { 4,7,2,1,5,3,8,6 };

    cout << "创建T1:" << endl;
    so.preCreate(T1);
    cout << "创建T1成功!" << endl;


    cout << "创建T2:" << endl;
    so.preCreate(T2);
    cout << "创建T2成功!" << endl;

    cout << "T1的前序遍历:" << endl;
    so.preOrder(T1);
    cout << endl;

    //cout << "T2的前序遍历:" << endl;
    //so.preOrder(T2);
    //cout << endl;

    cout << "T2是不是T1的子树:" << endl;
    bool result = so.HasSubtree(T1,T2);

    cout << result << endl;



    
    
    cout << endl;
    return 0;
}

转载于:https://www.cnblogs.com/wdan2016/p/5991063.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值