剑指offer-把二叉树打印成多行
题目描述
从上到下按层打印二叉树,同一层结点从左至右输出。每一层输出一行
题解:
使用bfs。
/* 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) { vector<vector<int> > ans; if(pRoot == NULL){ return ans; } TreeNode* tmp; queue<int> sq; sq.push(1); queue<TreeNode*> sqr; sqr.push(pRoot); int tmp_int, cur_layer = 1; vector<int> elem; while(!sqr.empty()){ tmp = sqr.front(); sqr.pop(); tmp_int = sq.front(); sq.pop(); if(tmp_int != cur_layer){ ans.push_back(elem); elem.clear(); cur_layer = tmp_int; } elem.push_back( tmp->val ); if(tmp->left){ sqr.push( tmp->left ); sq.push(tmp_int + 1); } if(tmp->right){ sqr.push( tmp->right ); sq.push(tmp_int + 1); } } ans.push_back(elem); return ans; } };