面試題55_1:二叉樹的深度

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

解題思路

  • 回溯法

上代碼(C++很香)

  回溯法,每次可以向左和向右走,最後統計最大的深度

int maxD = 0;

void dfs(TreeNode* pNode, int depth){
    // 葉子節點
    if(pNode->left == nullptr && pNode->right == nullptr){
        if(depth > maxD)
            maxD = depth;
        return ;
    }
    if(pNode->left != nullptr)
        dfs(pNode->left, depth + 1);
    if(pNode->right != nullptr)
        dfs(pNode->right, depth + 1);
}


int TreeDepth(TreeNode* pRoot){

    if(pRoot == nullptr)
        return 0;

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