• 数据结构练习(38)树的子结构


    http://zhedahht.blog.163.com/blog/static/25411174201011445550396/

    思路:

    2个递归,总体来说思路还是比较自然的。但是如何把代码写的优雅,包括一些边界的检查,还是一件需要雕琢的事情。

    文章中关于子树判断的递归处理的很好,代码十分精简:

    bool DoesTree1HaveAllNodesOfTree2(TreeNode* pTreeHead1, TreeNode* pTreeHead2)
    {
            if(pTreeHead2 == NULL)
                    return true;
     
            if(pTreeHead1 == NULL)
                    return false;
     
            if(pTreeHead1->m_nValue != pTreeHead2->m_nValue)
                    return false;
     
            return DoesTree1HaveAllNodesOfTree2(pTreeHead1->m_pLeft, pTreeHead2->m_pLeft) &&
                    DoesTree1HaveAllNodesOfTree2(pTreeHead1->m_pRight, pTreeHead2->m_pRight);
    }
    struct TreeNode {
        int m_value;
        TreeNode* m_lhs;
        TreeNode* m_rhs;
    };
    
    bool try2solve(TreeNode* pHead1, TreeNode* pHead2)
    {
        if (pHead2 == NULL)
            return true;
        if (pHead1 == NULL)
            return false;
    
        if (pHead1->m_value != pHead2->m_value)
            return false;
    
        return try2solve(pHead1->m_lhs, pHead2->m_lhs) && try2solve(pHead1->m_rhs, pHead2->m_rhs);
    }
    
    bool HasSubTree(TreeNode* pTreeHead1, TreeNode* pTreeHead2)
    {
        if (pTreeHead1 == NULL || pTreeHead2 == NULL)
            return false;
    
        bool result = false;
    
        if (pTreeHead1->m_value == pTreeHead2->m_value)
            result = try2solve(pTreeHead1, pTreeHead2);
    
        if (!result && pTreeHead1->m_lhs)
            result = HasSubTree(pTreeHead1->m_lhs, pTreeHead2);
        if (!result && pTreeHead1->m_rhs)
            result = HasSubTree(pTreeHead1->m_rhs, pTreeHead2);
    
        return result;
    }
    -------------------------------------------------------

    kedebug

    Department of Computer Science and Engineering,

    Shanghai Jiao Tong University

    E-mail: kedebug0@gmail.com

    GitHub: http://github.com/kedebug

    -------------------------------------------------------

  • 相关阅读:
    过渡效果
    生命周期
    事件处理
    列表的搜索和排序
    DotNetBar for Windows Forms 12.1.0.0_冰河之刃重打包版 原创发布
    DotNetBar for Windows Forms 11.8.0.8冰河之刃重打包版
    闲读
    POJ 3253 Fence Repair 贪心 优先级队列
    POJ 2431 Expedition 贪心 优先级队列
    优先级队列-堆-STL实现
  • 原文地址:https://www.cnblogs.com/kedebug/p/2828210.html
Copyright © 2020-2023  润新知