2014,計算二叉樹帶權路徑長度


思想:基於先序遍歷,用一個靜態變量保存WPL把每個節點的深度作為參數傳遞

若為葉子結點,WPL=該節點深度*權值,若非葉子節點則遞歸調用

代碼:

typedef struct BTNode
{
    int weight;
    struct BTNode *lchild,*rchild;

}BTNode,*BTree;
int WPL(BTree root)
{
    return WPL_CORE(root,0);
}
int WPL_CORE(BTree root,int deep)
{
    static wpl=0;
    if(root->lchild==NULL&&root->rchild==null)
        wpl+=deep*root->weight;
    if(root->lchild!=NULL)
        WPL_CORE(root->lchild,deep+1);
    if(root->rchild!=NULL)
        WPL_CORE(root->lchild,deep+1);
    return wpl;

}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM