public class LevelOrder {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> treeList = new ArrayList<>();
if (root == null) return treeList;
List<TreeNode> NodeList = new ArrayList<>();
NodeList.add(root);
while (!NodeList.isEmpty()) {
List<TreeNode> tempList = new ArrayList<>();
List<Integer> list = new ArrayList<>();
for (int i = 0; i < NodeList.size(); i++) {
list.add(NodeList.get(i).val);
if (NodeList.get(i).left != null) {
tempList.add(NodeList.get(i).left);
}
if (NodeList.get(i).right != null) {
tempList.add(NodeList.get(i).right);
}
}
treeList.add(list);
NodeList = tempList;
}
return treeList;
}
public 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;
}
}
}
二叉树层序遍历——leetcode
最新推荐文章于 2024-08-13 14:59:13 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)