二叉树的层序遍历,直接进行用二维vector进行层序,用一个queue进行,记录大小后,进行不断push进去。
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: vector<vector<int>> levelOrder(TreeNode* root) { vector<vector<int>> ans; if(!root) return ans; queue<TreeNode*> q; q.push(root); while(!q.empty()) { vector<int> tmp; int len = q.size(); while(len--) { TreeNode* t = q.front(); q.pop(); tmp.push_back(t->val); if(t->left) q.push(t->left); if(t->right) q.push(t->right); } ans.push_back(tmp); } return ans; } };