關於數據結構的學習經驗分享 (二叉樹相關的內容)

本文主要關於二叉樹的相關內容,

首先描述了二叉樹相關的基本代碼,然後總結了二叉樹基本的知識,最後概述了二叉樹相關的題目的總結

1.二叉樹基本數據結構描述 

struct BinaryTreeNode                 //定義了二叉樹節點信息
{
    int                    m_nValue;    //二叉樹的節點數據 
    BinaryTreeNode*        m_pLeft;     //左邊指針
    BinaryTreeNode*        m_pRight;    //右邊指針
};

BinaryTreeNode* CreateBinaryTreeNode(int value);         //創建二叉樹節點
void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight);  //鏈接二叉樹節點
 void PrintTreeNode(BinaryTreeNode* pNode);       //打印二叉樹節點
 void PrintTree(BinaryTreeNode* pRoot);          //打印二叉樹
void DestroyTree(BinaryTreeNode* pRoot);         //銷燬二叉樹


// 《劍指Offer——名企面試官精講典型編程題》代碼
// 著作權所有者:何海濤

#include "StdAfx.h"
#include "BinaryTree.h"

BinaryTreeNode* CreateBinaryTreeNode(int value)             //創建二叉樹節點
{
    BinaryTreeNode* pNode = new BinaryTreeNode();
    pNode->m_nValue = value;
    pNode->m_pLeft = NULL;
    pNode->m_pRight = NULL;

    return pNode;
}

void ConnectTreeNodes(BinaryTreeNode* pParent, BinaryTreeNode* pLeft, BinaryTreeNode* pRight)  //鏈接二叉樹節點
{
    if(pParent != NULL)
    {
        pParent->m_pLeft = pLeft;
        pParent->m_pRight = pRight;
    }
}

void PrintTreeNode(BinaryTreeNode* pNode)                             //注意判斷條件
{
    if(pNode != NULL)
    {
        printf("value of this node is: %d\n", pNode->m_nValue);

        if(pNode->m_pLeft != NULL)
            printf("value of its left child is: %d.\n", pNode->m_pLeft->m_nValue);
        else
            printf("left child is null.\n");

        if(pNode->m_pRight != NULL)
            printf("value of its right child is: %d.\n", pNode->m_pRight->m_nValue);
        else
            printf("right child is null.\n");
    }
    else
    {
        printf("this node is null.\n");
    }

    printf("\n");
}

void PrintTree(BinaryTreeNode* pRoot)      //  需要判斷 
{
    PrintTreeNode(pRoot);

    if(pRoot != NULL)
    {
        if(pRoot->m_pLeft != NULL)
            PrintTree(pRoot->m_pLeft);

        if(pRoot->m_pRight != NULL)
            PrintTree(pRoot->m_pRight);
    }
}

void DestroyTree(BinaryTreeNode* pRoot)
{
    if(pRoot != NULL)
    {
        BinaryTreeNode* pLeft = pRoot->m_pLeft;
        BinaryTreeNode* pRight = pRoot->m_pRight;     //一定要住一順序  遞歸的順序  首先總結重複步驟 ,歸納重複步驟,最後遞歸 

        delete pRoot;
        pRoot = NULL;

        DestroyTree(pLeft);
        DestroyTree(pRight);
    }
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章