102.二叉樹的層序遍歷

一、思路:

二叉樹層序遍歷使用隊列:一個結點出隊時將它的左右孩子放入隊列,依次循環打印(循環條件爲隊列非空);

當需要按行打印時,需引入last和nlast兩個指針,last指向當前行的最後一個結點,nlast指向下一行的最後一個結點(每次指向新入隊的結點,該結點一定是目前下一行的最後一個結點);當last指向的結點出隊時,令last=nlast即可。

二、代碼(c++):

    vector<vector<int>> levelOrder(TreeNode* root) {
        if(root==NULL)    //二叉樹爲空的特例
            return {};
        vector<vector<int>> res;    //存放結果
        vector<int> line;    //存放層序遍歷的一行
        TreeNode *last=root, *nlast, *r=root;    //last指向當前行最後一個元素,nlsat指向下一行最後一個元素
        queue<TreeNode*> print_q;    //層序遍歷的隊列
        print_q.push(root);    //將根節點放入隊列
        while(print_q.size())    //循環條件爲隊列非空
        {
            line.push_back(print_q.front()->val);    //存放隊列首元素
            TreeNode *r=print_q.front();    //記錄隊首元素
            print_q.pop();    //首元素出隊
            if(r->left)    //如果結點非空,將結點的左孩子放入隊列
            {
                print_q.push(r->left);    
                nlast=r->left;    //nlast始終跟蹤新入隊的結點
            }   
            if(r->right)
            {
                print_q.push(r->right);
                nlast=r->right;
            }
            if(r==last)    //當last指向的結點出隊時,令last=nlast
            {
                last=nlast;
                res.push_back(line);    //line結束記錄並放入res中
                vector<int> n;
                line=n;    //將line置爲空
            }
        }
        return res;
    }

 

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