層次遍歷二叉樹

  • 從上往下打印出二叉樹的每個節點,同層節點從左至右打印。
  • 數據結構基本算法
    vector<int> PrintFromTopToBottom(TreeNode* root) {
        //層次遍歷二叉樹 需要隊列輔助
        queue<TreeNode*> que;
        vector<int> ans;
        TreeNode* point;
        que.push(root);
        while(!que.empty())
        {
            point = que.front();
            if(point != NULL)               //非空節點
            {
                ans.push_back(point->val);
                if(point->left!= NULL)            //加入左樹
                que.push(point->left);
                if(point->right!= NULL)             //加入右樹
                que.push(point->right);
            }
            que.pop();
            
        }
        return ans;
    }

在這裏插入圖片描述

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