树的子结构

一、前言

继续树相关的问题

 

二、题目

输入两棵二叉树A和B,判断B是不是A的子结构。

 

三、思路

递归实现即可

 

四、编码实现

之前创建树是通过前序遍历和中序遍历来重建树,这种方法要求不能有相同的值。树的子结构需要考虑有相同的结点值。新增一直构造树的方法,类似组合模式。当前提供了三种构建树方法。

// ConstructTree.h
#pragma once
#include <exception>
#include "Common.h"


// 构造普通树(不含父指针)START
template<class T>
BinaryTreeNode<T>* ConstructTreeOperate(T* startPreorder, T* endPreorder, T* startInorder, T* endInorder);

template<class T>
BinaryTreeNode<T>* ConstructTree(T* preorder, T* inorder, int length)
{
    if (preorder == nullptr || inorder == nullptr || length <= 0)
        return nullptr;

    return ConstructTreeOperate(preorder, preorder + length - 1,
        inorder, inorder + length - 1);
}

template<class T>
BinaryTreeNode<T>* ConstructTreeOperate
(
    T* startPreorder, T* endPreorder,
    T* startInorder, T* endInorder
)
{
    // 前序遍历序列的第一个数字是根结点的值
    T rootValue = startPreorder[0];
    BinaryTreeNode<T>* root = new BinaryTreeNode<T>();
    root->m_nValue = rootValue;
    root->m_pLeft = root->m_pRight = nullptr;

    if (startPreorder == endPreorder)
    {
        if (startInorder == endInorder && *startPreorder == *startInorder)
            return root;
        else
            throw std::exception("Invalid input.");
    }

    // 在中序遍历中找到根结点的值
    T* rootInorder = startInorder;
    while (rootInorder <= endInorder && *rootInorder != rootValue)
        ++rootInorder;

    if (rootInorder == endInorder && *rootInorder != rootValue)
        throw std::exception("Invalid input.");

    int leftLength = int(rootInorder - startInorder);
    T* leftPreorderEnd = startPreorder + leftLength;
    if (leftLength > 0)
    {
        // 构建左子树
        root->m_pLeft = ConstructTreeOperate(startPreorder + 1, leftPreorderEnd,
            startInorder, rootInorder - 1);
    }
    if (leftLength < endPreorder - startPreorder)
    {
        // 构建右子树
        root->m_pRight = ConstructTreeOperate(leftPreorderEnd + 1, endPreorder,
            rootInorder + 1, endInorder);
    }

    return root;
}
// 构造普通树(不含父指针)END




// 构造有父指针的树(含父指针)START
template<class T>
BinaryTreeNode_ParentNode<T>* ConstructParentNodeTreeOperate(T* startPreorder, T* endPreorder, T* startInorder, T* endInorder, BinaryTreeNode_ParentNode<T>* parentNode);

template<class T>
BinaryTreeNode_ParentNode<T>* ConstructParentNodeTree(T* preorder, T* inorder, int length)
{
    if (preorder == nullptr || inorder == nullptr || length <= 0)
        return nullptr;

    BinaryTreeNode_ParentNode<T>* pRoot = new BinaryTreeNode_ParentNode<T>();
    return ConstructParentNodeTreeOperate(preorder, preorder + length - 1,
        inorder, inorder + length - 1, pRoot);
}

template<class T>
BinaryTreeNode_ParentNode<T>* ConstructParentNodeTreeOperate
(
    T* startPreorder, T* endPreorder,
    T* startInorder, T* endInorder,
    BinaryTreeNode_ParentNode<T>* parentNode
)
{
    // 前序遍历序列的第一个数字是根结点的值
    T rootValue = startPreorder[0];
    BinaryTreeNode_ParentNode<T>* root = new BinaryTreeNode_ParentNode<T>();
    root->m_nValue = rootValue;
    root->m_pLeft = root->m_pRight = nullptr;
    root->m_pParent = parentNode;
    if (startPreorder == endPreorder)
    {
        if (startInorder == endInorder && *startPreorder == *startInorder)
            return root;
        else
            throw std::exception("Invalid input.");
    }

    // 在中序遍历中找到根结点的值
    T* rootInorder = startInorder;
    while (rootInorder <= endInorder && *rootInorder != rootValue)
        ++rootInorder;

    if (rootInorder == endInorder && *rootInorder != rootValue)
        throw std::exception("Invalid input.");

    int leftLength = int(rootInorder - startInorder);
    T* leftPreorderEnd = startPreorder + leftLength;
    if (leftLength > 0)
    {
        // 构建左子树
        root->m_pLeft = ConstructParentNodeTreeOperate(startPreorder + 1, leftPreorderEnd,
            startInorder, rootInorder - 1, root);
    }
    if (leftLength < endPreorder - startPreorder)
    {
        // 构建右子树
        root->m_pRight = ConstructParentNodeTreeOperate(leftPreorderEnd + 1, endPreorder,
            rootInorder + 1, endInorder, root);
    }

    return root;
}
// 构造有父指针的树(含父指针)END




// 通过组合的方式构造树 (不含父指针)START
template<class T>
class ComponentConstructTree: public BinaryTreeNode<T>
{
public:
    ComponentConstructTree(T value)
    {
        m_nValue = value;
        m_pLeft = nullptr;
        m_pRight = nullptr;
    }

    virtual void AddLeft(BinaryTreeNode<T>* pLeft) { m_pLeft = pLeft; };
    virtual void AddRight(BinaryTreeNode<T>* pRight) { m_pRight = pRight; };
    virtual void AddLeft(BinaryTreeNode<T> pLeft) { m_pLeft = &pLeft; };
    virtual void AddRight(BinaryTreeNode<T> pRight) { m_pRight = &pRight; };
    virtual void Add(BinaryTreeNode<T>* pLeft, BinaryTreeNode<T>* pRigh) { m_pLeft = pLeft; m_pRight = pRigh; };
    virtual void Add(BinaryTreeNode<T> pLeft, BinaryTreeNode<T> pRigh) { m_pLeft = &pLeft; m_pRight = &pRigh; };
};
// 通过组合的方式构造树(不含父指针)END

树的子结构判断

// HasSubtree.h
#pragma once
#include "Common.h"
#include "ConstructTree.h"

#define NAMESPACE_HASSUBTREE namespace NAME_HASSUBTREE {
#define NAMESPACE_HASSUBTREEEND }

template<class T>
bool DoesTreeAHaveTreeB(BinaryTreeNode<T>* pRootA, BinaryTreeNode<T>* pRootB);

template<class T>
bool HasSubtree(BinaryTreeNode<T>* pRootA, BinaryTreeNode<T>* pRootB)
{
    if (pRootA == nullptr || pRootB == nullptr)
    {
        return false;
    }

    bool retsult = false;

    if (pRootA->m_nValue == pRootB->m_nValue)
    {
        retsult = DoesTreeAHaveTreeB(pRootA, pRootB);
    }

    if (!retsult)
    {
        retsult = HasSubtree(pRootA->m_pLeft, pRootB);
    }

    if (!retsult)
    {
        retsult = HasSubtree(pRootA->m_pRight, pRootB);
    }

    return retsult;
}

// pRootA 中包含 pRootB, 且是从根节点开始包含
template<class T>
bool DoesTreeAHaveTreeB(BinaryTreeNode<T>* pRootA, BinaryTreeNode<T>* pRootB)
{
    
    if (pRootB == nullptr)
    {
        return true;
    }

    if (pRootA == nullptr)
    {
        return false;
    }

    if (pRootA->m_nValue != pRootB->m_nValue)
    {
        return false;
    }

    return DoesTreeAHaveTreeB(pRootA->m_pLeft, pRootB->m_pLeft) && DoesTreeAHaveTreeB(pRootA->m_pRight, pRootB->m_pRight);
}
//
// 测试 用例 START
NAMESPACE_HASSUBTREE

template<class T>
void test(const char* testName, BinaryTreeNode<T>* pRootA, BinaryTreeNode<T>* pRootB, bool expect)
{
    bool result = HasSubtree(pRootA, pRootB);

    if (result == expect)
    {
        cout << testName << "solution passed." << endl;
    }
    else
    {
        cout << testName << "solution failed." << endl;
    }
}

// 普通二叉树 A
//               8(a)
//            /       \
//           8(b)      7(c)  
//         /   \     
//        9(d)  2(e)   
//             / \     
//          4(h)  7(i) 
ComponentConstructTree<int>* GetTreeA()
{
    ComponentConstructTree<int>* pRoot = new ComponentConstructTree<int>(8);
    ComponentConstructTree<int>* pNode_b = new ComponentConstructTree<int>(8);
    ComponentConstructTree<int>* pNode_c = new ComponentConstructTree<int>(7);
    ComponentConstructTree<int>* pNode_d = new ComponentConstructTree<int>(9);
    ComponentConstructTree<int>* pNode_e = new ComponentConstructTree<int>(2);
    ComponentConstructTree<int>* pNode_h = new ComponentConstructTree<int>(4);
    ComponentConstructTree<int>* pNode_i = new ComponentConstructTree<int>(7);

    pRoot->Add(pNode_b, pNode_c);
    pNode_b->Add(pNode_d, pNode_e);
    pNode_e->Add(pNode_h, pNode_i);

    return pRoot;
}

template<class T>
void ReleaseTree(ComponentConstructTree<T>* pRoot)
{
    if (pRoot == nullptr)
    {
        return;
    }

    ReleaseTree((ComponentConstructTree<T>*)pRoot->m_pLeft);
    ReleaseTree((ComponentConstructTree<T>*)pRoot->m_pRight);

    delete pRoot;
}

// 普通二叉树 B
//           8(b)        
//         /   \     
//        9(d) 2(e) 
void Test1()
{
    ComponentConstructTree<int>* pRootA = GetTreeA();

    ComponentConstructTree<int> pRootB(8);
    ComponentConstructTree<int> pNode_p(9);
    ComponentConstructTree<int> pNode_q(2);
    // pRootB:需要从下往上创建
    pRootB.Add(pNode_p, pNode_q);

    bool expect = true;
    test("Test1()", (BinaryTreeNode<int>*)pRootA, &(BinaryTreeNode<int>)pRootB, expect);

    // 申请的内存需要手动释放
    ReleaseTree(pRootA);
}

// 普通二叉树 B
//           8(b)     
//             \     
//              2(e)   
//               \     
//                7(i) 
void Test2()
{
    ComponentConstructTree<int>* pRootA = GetTreeA();

    ComponentConstructTree<int> pRootB(8);
    ComponentConstructTree<int> pNode_e(2);
    ComponentConstructTree<int> pNode_i(7);
    // pRootB:需要从下往上创建
    pNode_e.AddRight(pNode_i);
    pRootB.AddRight(pNode_e);
   
    bool expect = true;
    test("Test2()", (BinaryTreeNode<int>*)pRootA, &(BinaryTreeNode<int>)pRootB, expect);

    // 申请的内存需要手动释放
    ReleaseTree(pRootA);
}

// 普通二叉树 B
//           8(b)     
//             \     
//              2(e)   
//               \     
//                10 
void Test3()
{
    ComponentConstructTree<int>* pRootA = GetTreeA();

    ComponentConstructTree<int> pRootB(8);
    ComponentConstructTree<int> pNode_e(2);
    ComponentConstructTree<int> pNode_i(10);
    
    // pRootB:需要从下往上创建
    pNode_e.AddRight(pNode_i);
    pRootB.AddRight(pNode_e);

    bool expect = false; //【没有子结构】
    test("Test3()", (BinaryTreeNode<int>*)pRootA, &(BinaryTreeNode<int>)pRootB, expect);

    // 申请的内存需要手动释放
    ReleaseTree(pRootA);
}

// 普通二叉树 B
//               8(a)
//            /       \
//           8(b)      7(c)  
//         /   \     
//        9(d)  2(e)   
//             /     
//          4(h)  
void Test4()
{
    ComponentConstructTree<int>* pRootA = GetTreeA();

    ComponentConstructTree<int> pRootB(8);
    ComponentConstructTree<int> pNode_b(8);
    ComponentConstructTree<int> pNode_c(7);
    ComponentConstructTree<int> pNode_d(9);
    ComponentConstructTree<int> pNode_e(2);
    ComponentConstructTree<int> pNode_h(4);

    // pRootB:需要从下往上创建
    pNode_e.AddLeft(pNode_h);
    pNode_b.Add(pNode_d,pNode_e);

    pRootB.Add(pNode_b, pNode_c);

    bool expect = true; 
    test("Test4()", (BinaryTreeNode<int>*)pRootA, &(BinaryTreeNode<int>)pRootB, expect);

    // 申请的内存需要手动释放
    ReleaseTree(pRootA);
}

NAMESPACE_HASSUBTREEEND
// 测试 用例 END
//

void HasSubtree_Test()
{
    NAME_HASSUBTREE::Test1();
    NAME_HASSUBTREE::Test2();
    NAME_HASSUBTREE::Test3();
    NAME_HASSUBTREE::Test4();
}

执行结果:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值