Leetcode 之Binary Tree Postorder Traversal(45)
层序遍历,使用队列将每层压入,定义两个队列来区分不同的层。
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
vector<vector<int>> levelorderTraversal(TreeNode *root) { vector<vector<int>> result; vector<int>tmp; //通过两个queue来区分不同的层次 queue<TreeNode *>current,next; TreeNode *p = root; current.push(p); while (!current.empty()) { while (!current.empty()) { p = current.front(); current.pop(); tmp.push_back(p->val); if (p->left != nullptr)next.push(p->left); if (p->right != nullptr)next.push(p->right); } result.push_back(tmp); tmp.clear(); //交换并将next清空, swap(current, next); } return result; }