劍指offer_編程題_把二叉樹打印成多行

  • 題目
    從上到下按層打印二叉樹,同一層結點從左至右輸出。
    每一層輸出一行。
    
  1. 按層序遍歷
    /*
    struct TreeNode {
        int val;
        struct TreeNode *left;
        struct TreeNode *right;
        TreeNode(int x) :
                val(x), left(NULL), right(NULL) {
        }
    };
    */
    class Solution {
    public:
            vector<vector<int> > Print(TreeNode* pRoot) {
                std::vector<std::vector<int>> res;
         	   if (pRoot==NULL)
         		   return res;
         	   std::queue<TreeNode*> q;
         	   q.push(pRoot);
         	   while(!q.empty())
         	   {
         		   int length = q.size();
         		   std::vector<int> temp;
         		   for (int i = 0; i < length; ++i)
         		   {
         			   TreeNode* now = q.front();
         			   temp.push_back(now->val);
         			   q.pop();
         			   if (now->left!=NULL)
         				   q.push(now->left);
         			   if (now->right!=NULL)
         				   q.push(now->right);
         		   }
         		   res.push_back(temp);
         	   }
         	   return res;
            }
    };
    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章