![5fa59846037c91c074525c8997d63b96.png](https://i-blog.csdnimg.cn/blog_migrate/ce97ba994213558b7093561350ac2cea.jpeg)
LeetCode算法-102. 二叉树的层序遍历
102. 二叉树的层序遍历
题目
给你一个二叉树,请你返回其按 层序遍历 得到的节点值。(即逐层地,从左到右访问所有节点)。
示例:二叉树:[3,9,20,null,null,15,7],
3
/ \
9 20
/ \
15 7
返回其层次遍历结果:
[
[3],
[9,20],
[15,7]
]
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/binary-tree-level-order-traversal 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
题解
Java
public List> levelOrder(TreeNode root) {
List> list = new ArrayList>();if (root == null) {return list;
}
Queue queue = new LinkedList();
queue.add(root);while (!queue.isEmpty()) {int size = queue.size();
List subList = new ArrayList();for (int i = 0; i
TreeNode node = queue.poll();
subList.add(node.val);if (node.left != null) {
queue.add(node.left);
}if (node.right != null) {
queue.add(node.right);
}
}
list.add(subList);
}return list;
}
C++
vector<vector<int> > levelOrder1(TreeNode *root) {
queue q;vectorvector<int> > vv;vector<int> v;if (root){
v.push_back(root->val);
vv.push_back(v);
}
q.push(root);int i=0;vector vt; while(q.size()>0){
TreeNode *p = q.front();
q.pop();
vt.push_back(p); if ( p==NULL ) {continue;
}
q.push(p->left);
q.push(p->right);
}int step = 2;int j; for (int i=1; i v.clear();int cnt=0;for (j=i; j if (vt[j]) {
v.push_back(vt[j]->val);
cnt += 2;
}
}
step = cnt;if (v.size()>0) {
vv.push_back(v);
}
}return vv;
}vector<vector<int> > levelOrder2(TreeNode *root) {vectorvector<int> > vv;vector<int> v;if (root){
v.push_back(root->val);
vv.push_back(v);
}vectorvector<int> > vv_left, vv_right;if(root && root->left) {
vv_left = levelOrder2(root->left);
}if(root && root->right) {
vv_right = levelOrder2(root->right);
}//mergefor(int i=0; i if (i vv_left[i].insert(vv_left[i].end(), vv_right[i].begin(), vv_right[i].end());
vv.push_back(vv_left[i]);
}else if (i vv.push_back(vv_left[i]);
}else {
vv.push_back(vv_right[i]);
}
}return vv;
}vector<vector<int> > levelOrder3(TreeNode *root) {vectorvector<int> > vv;if(root == NULL) return vv;int level = 0; // current level.
TreeNode *last = root; // last node of currrent level.queue q;
q.push(root);
vv.push_back(vector<int>());while(!q.empty()) {
TreeNode *p = q.front();
q.pop();
vv[level].push_back(p->val);if(p->left ) q.push(p->left);if(p->right) q.push(p->right);if(p == last) {
level++;
last = q.back();
vv.push_back(vector<int>()); // new buffer for next row.
}
}
vv.pop_back();return vv;
}
更多干货文章
博客:www.qiuxuewei.com
微信公众号:「@开发者成长之路」
「一个没有鸡汤只有干货的公众号」