题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行。
解题思路:可以直到,每次打印一个结点,然后打印下一行时总是先打印其左子结点,然后打印其右子结点。先入先出,使用队列处理。使用toBeprint记录当前行打印的个数,每存入一个-1;nextlevel记录下一行打印结点个数;一行打印完,toBeprint = nextlevel;nextlevel = 0;
1 /* 2 struct TreeNode { 3 int val; 4 struct TreeNode *left; 5 struct TreeNode *right; 6 TreeNode(int x) : 7 val(x), left(NULL), right(NULL) { 8 } 9 }; 10 */ 11 class Solution { 12 public: 13 vector<vector<int> > Print(TreeNode* pRoot) { 14 vector<vector<int> > result; 15 vector<int> temp;//间接变量,存储一行 16 if(pRoot == NULL) 17 return result; 18 queue<TreeNode *> nodes; 19 nodes.push(pRoot); 20 int nextlevel = 0;//下一行应打印个数 21 int toBePrint = 1;//当前行剩余打印个数 22 while(!nodes.empty()) 23 { 24 TreeNode *pNode = nodes.front(); 25 temp.push_back(pNode->val); 26 if(pNode->left != NULL) 27 { 28 nodes.push(pNode->left); 29 ++nextlevel; 30 } 31 if(pNode->right != NULL) 32 { 33 nodes.push(pNode->right); 34 ++nextlevel; 35 } 36 nodes.pop(); 37 --toBePrint; 38 if(toBePrint == 0)//一行已打印完 39 { 40 result.push_back(temp); 41 temp.clear();//清空 42 toBePrint = nextlevel; 43 nextlevel = 0; 44 } 45 } 46 return result; 47 } 48 };