题解 | #求二叉树的层序遍历#
求二叉树的层序遍历
https://www.nowcoder.com/practice/04a5560e43e24e9db4595865dc9c63a3
/** * struct TreeNode { * int val; * struct TreeNode *left; * struct TreeNode *right; * }; */ class Solution { public: /** * * @param root TreeNode类 * @return int整型vector<vector<>> */ void levelOrder_per(vector<vector<int>>& resultvalues, queue<TreeNode*>& tempq) { queue<TreeNode*> newqueue; vector<int>tempin; while (!tempq.empty()) { TreeNode* temptreenode = tempq.front(); tempq.pop(); tempin.push_back(temptreenode->val); if (temptreenode->left)newqueue.push(temptreenode->left); if (temptreenode->right)newqueue.push(temptreenode->right); if (tempq.empty()) { resultvalues.push_back(tempin); tempin.clear(); swap(tempq, newqueue);//交换队列(把空队列转给newqueue,把newqueue交给tempq接续遍历) } } } vector<vector<int> > levelOrder(TreeNode* root) { vector<vector<int>> tempresult; queue<TreeNode*> tempq; tempq.push(root); if (root == nullptr)return tempresult; levelOrder_per(tempresult, tempq); return tempresult; } };