层序遍历
注意:
1,使用队列的形式,依次入队,同时对队列进行计数
2,知道数目消失,才进行下一个队列
代码:
1 vector<vector<int>> levelOrder(TreeNode* root) 2 { 3 vector<vector<int>> result; 4 if (root == NULL) return result; 5 queue<TreeNode*> selected; 6 7 selected.push(root); 8 while (!selected.empty()) 9 { 10 vector<int> valueItem; 11 int nodeCountByLayer = selected.size(); 12 while (nodeCountByLayer != 0) 13 { 14 auto top_ = selected.front(); 15 selected.pop(); 16 17 valueItem.push_back(top_->val); 18 if (top_->left != NULL) selected.push(top_->left); 19 if (top_->right != NULL) selected.push(top_->right); 20 21 nodeCountByLayer--; 22 } 23 24 result.push_back(valueItem); 25 } 26 27 return result; 28 }
标签:优先,递归,top,selected,_-,二叉树,push,result From: https://www.cnblogs.com/smartisn/p/17495554.html