求二叉樹的寬度

二叉樹的寬度:樹中最大的層節點數。
主要思路爲:樹不爲空時,初始化父節點數(LastLevelWidth)爲1(即頭結點pop進隊列),通過判斷queue是否爲空表示樹全部節點遍歷完成,以父結點數(LastLevelWidth)爲while條件計算當層子結點數(CurLevelWidth更新LastLevelWidth,實現逐層遍歷),當減自爲0即表示該層結點遍歷完成,將遍歷的節點push進隊列。每次都用?:記錄最大的節點數,以便輸出樹的寬度。

typedef struct Node{
    int data;
    struct Node *Lchild,Node *Rchild;
}TreeNode;

int CountWidth(TreeNode *root)
{
    if(root == NULL)
        return 0;

    int LastLevelWidth = 0;
    int CurLevelWidth = 0;
    int initWidth = 1;

    queue<TreeNode *> myQueue;
    myQueue.push(root);
    LastLevelWidth = 1;

    TreeNode *cur = NULL;

    while(!myQueue.empty()) 
    {
        while(LastLevelWidth != 0)
        {
            cur = myQueue.front();  
            myQueue.pop();
            if(cur->Lchild != NULL)
                myQueue.push(cur->Lchild);
            if(cur->.Rchild != NULL)
                myQueue.push(cur->Rchild);

            LastLevelWidth--;
        }

        CurLevelWidth = myQueue.size();//父結點數遍歷完畢即隊列內的便是當前層子結點
        initWidth = LastLevelWidth > CurLevelWidth ? LastLevelWidt
                    : CurLevelWidth;    //記錄最大結點數
        LastLevelWidth = CurLevelWidth;//更新,以便獲取下一層結點數
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章