问题
给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。
例子

思路
- 队列存储结点
- 获取每层的个数width,然后从队列中拉出来width个结点
代码
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> list = new ArrayList<>();
if(root==null) return list;
Queue<TreeNode> q = new LinkedList<>();
q.offer(root);
while(!q.isEmpty()) {
int width = q.size();//该层的结点个数
List<Integer> list2 = new ArrayList<>();
for(int i=0; i<width; i++){
TreeNode node = q.poll();
list2.add(node.val);
if(node.left!=null) q.offer(node.left);
if(node.right!=null) q.offer(node.right);
}
list.add(list2);
}
return list;
}
}

本文介绍了一种使用队列实现的二叉树层次遍历算法。通过存储每层节点并逐层访问,实现了从左至右的节点值遍历。代码示例展示了如何用Java实现这一算法。
349

被折叠的 条评论
为什么被折叠?



