Closed PisecesPeng closed 3 years ago
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() { }
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static List<List<Integer>> func(TreeNode root) {
List<TreeNode> tmpList = new ArrayList<>();
if (null != root) tmpList.add(root);
List<List<Integer>> x = new ArrayList<>(); // 存放结果
while (tmpList.size() > 0) {
// 将本层的节点复制到新list中, 并将老list清空
List<TreeNode> tmp = new ArrayList();
tmp.addAll(tmpList);
tmpList.clear();
List<Integer> y = new ArrayList<>();
for (TreeNode node : tmp) {
// 将本层的值统计
y.add(node.val);
// 将本层的节点按顺序添加, 为下一次循环
if (null != node.left)
tmpList.add(node.left);
if (null != node.right)
tmpList.add(node.right);
}
x.add(y);
}
return x;
}
class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode() { }
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static List<List<Integer>> func(TreeNode root) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
if (root == null) {
return ret;
}
Queue<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while (!queue.isEmpty()) {
List<Integer> level = new ArrayList<Integer>();
int currentLevelSize = queue.size();
for (int i = 1; i <= currentLevelSize; ++i) {
TreeNode node = queue.poll();
level.add(node.val);
if (node.left != null) {
queue.offer(node.left);
}
if (node.right != null) {
queue.offer(node.right);
}
}
ret.add(level);
}
return ret;
}
二叉树的层序遍历
给你一个二叉树,
请你返回其按层序遍历得到的节点值.(即逐层地,从左到右访问所有节点).
示例:
二叉树:
[3,9,20,null,null,15,7]
,返回其层次遍历结果:
题目地址: https://leetcode-cn.com/problems/binary-tree-level-order-traversal/