劍指offer之二叉樹的深度

1.題目描述

輸入一棵二叉樹,求該樹的深度。從根結點到葉結點依次經過的結點(含根、葉結點)形成樹的一條路徑,最長路徑的長度爲樹的深度。

2.問題分析

方法一:

可以使用遞歸的方法,分別求左子樹和右子樹的深度,則樹的深度是:更大者 + 1。這是一個遞歸的方法。

方法二:

使用層次遍歷的方法,每訪問一層,則深度+1,所有層的訪問結束之後,就等到深度了。這裏需要使用到一個隊列,來幫助我們層次遍歷,這不是一個遞歸的方法

3.源代碼

方法一:

int TreeDepth(TreeNode* pRoot)
{
    if(pRoot == NULL)
        return 0;
    int left = TreeDepth(pRoot->left);
    int right = TreeDepth(pRoot->right);
    return (left + 1 > right + 1) ? left + 1:right + 1;
}

方法二:

int TreeDepth(TreeNode* pRoot)
{
    if(pRoot == NULL)
        return 0;
    queue<TreeNode*> nodes;
    nodes.push(pRoot);
    int deep = 0;
    int curCount = 1;
    int nextCount = 0;
    while(!nodes.empty())
    {
        TreeNode* node = nodes.front();
        nodes.pop();
        --curCount;
        if(node->left != NULL)
        {
            ++nextCount;
            nodes.push(node->left);
        }
        if(node->right != NULL)
        {
            ++nextCount;
            nodes.push(node->right);
        }
        if(curCount == 0)
        {
            curCount = nextCount;
            nextCount = 0;
            ++deep;
        }
    }
    return deep;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章