두 갈래 나무의 깊이 코드 구현을 구하다

귀속 방안으로 실현:
/*   */
int getDepthBiTree(BITREENODE* T)
{
    int lDepth = 0, rDepth = 0;

    if(T == NULL)
    {
        return 0;
    }
    else
    {
        lDepth = getDepthBiTree(T->lchild);
        rDepth = getDepthBiTree(T->rchild);
    }

    return lDepth > rDepth ? lDepth+1 : rDepth+1;
}

전체 코드:
#include 
#include 
#include 
#include 

using namespace std;

/*  */
typedef char TypeData;
typedef struct BiTreeNode
{
    TypeData data;
    struct BiTreeNode *lchild, *rchild;
}BITREENODE;


BITREENODE* createBiTree();          /*   */
void preOrderBiTree(BITREENODE* T);  /*   */


/*   */
BITREENODE* createBiTree()
{
    TypeData ch = 0;
    BITREENODE* pNewNode = NULL;

    cin >> ch;

    if(ch == '#')
    {
        pNewNode = NULL;
    }
    else
    {
        /*   */
        pNewNode = (BITREENODE*)malloc(sizeof(BITREENODE));
        pNewNode->data = ch;

        /*   */
        pNewNode->lchild = createBiTree();
        pNewNode->rchild = createBiTree();
    }

    return pNewNode;
}

/*   */
void preOrderBiTree(BITREENODE* T)
{
    if(T)
    {
       cout << T->data << " ";
       preOrderBiTree(T->lchild);
       preOrderBiTree(T->rchild);
    }
}

/*   */
int getDepthBiTree(BITREENODE* T)
{
    int lDepth = 0, rDepth = 0;

    if(T == NULL)
    {
        return 0;
    }
    else
    {
        lDepth = getDepthBiTree(T->lchild);
        rDepth = getDepthBiTree(T->rchild);
    }

    return lDepth > rDepth ? lDepth+1 : rDepth+1;
}

int main(void)
{
    BITREENODE* pRoot = NULL;
    int depth = 0;

    /*   */
    pRoot = createBiTree();

    /*  , ,  */
    preOrderBiTree(pRoot);
    cout << endl;

    /*  */
    depth = getDepthBiTree(pRoot);
    cout << depth << endl;


    return 0;
}

좋은 웹페이지 즐겨찾기