vlambda博客
学习文章列表

day7 二叉树的层次遍历

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<>> */ vector<vector<int> > levelOrder(TreeNode* root) { // write code here if(root == NULL) return {}; vector<vector<int> > re; queue<TreeNode*> q; q.push(root); while(!q.empty()){ int n = q.size(); vector<int> temp; for(int i=0;i<n;++i){ temp.push_back(q.front()->val); if(q.front()->left) q.push(q.front()->left); if(q.front()->right) q.push(q.front()->right); q.pop(); } re.push_back(temp); } return re; }};