首页 > 代码库 > something about basic usage of vector,queue
something about basic usage of vector,queue
1.for a two dimension vector, we must assign at least the first dimension of the vector
2.each dimension of an inner vector can be different
3.if you don‘t want to set a volume for vector<vector<int> > for uncertainness, you can just use a method like append to implement the structure,which is applied inBinary Tree Level Order Traversal,
4.about queue: to add an element, q.push(element); to get the first element, q.front(); to erase the first element, q.pop();
5.how to differ elements from different layers?
use two queues rather than one
code:
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | class Solution{ public : vector<vector< int > > levelOrder(TreeNode*root){ vector<vector< int > > matrix; if (root == NULL){ return matrix; } queue<TreeNode*> qNode[2]; //int row = 0; qNode[0].push(root); int index = 0; while ((!qNode[0].empty())||(!qNode[1].empty())){ vector< int >mm; switch (index){ case (0): while (!qNode[0].empty()){ TreeNode* tmp = qNode[0].front(); qNode[0].pop(); mm.push_back(tmp->val); if (tmp->left != NULL){ qNode[1].push(tmp->left); } if (tmp->right != NULL){ qNode[1].push(tmp->right); } } index = 1 - index; matrix.push_back(mm); //++row; break ; case (1): //vector<vector<int> >m; while (!qNode[1].empty()){ TreeNode* tmp = qNode[1].front(); qNode[1].pop(); //matrix[row].push_back(tmp->val); mm.push_back(tmp->val); if (tmp->left != NULL){ qNode[0].push(tmp->left); } if (tmp->right!=NULL){ qNode[0].push(tmp->right); } } index = 1 - index; //++row; matrix.push_back(mm); } } return matrix; } }; |
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。