# 二叉树层序遍历为二维数组

## 样例

```    3
/ \
5   2
/ \ / \
8  3 4  1         ```

## 代码实现

```import java.util.*;

/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}*/
public class TreePrinter {
public int[][] printTree(TreeNode root) {
ArrayList<ArrayList<TreeNode>> levelList = new ArrayList<ArrayList<TreeNode>>();
ArrayList<TreeNode> level = new ArrayList<TreeNode>();

TreeNode last = root;
TreeNode nlast = null;

while (!queue.isEmpty()) {
TreeNode pollNode = queue.poll();
if (pollNode.left != null) {
nlast = pollNode.left;
}

if (pollNode.right != null) {
nlast = pollNode.right;
}
if (last == pollNode) {
last = nlast;
level = new ArrayList<TreeNode>();
}
}

int[][] rs = new int[levelList.size()][];
for (int i = 0; i < levelList.size(); i++) {
rs[i] = new int[levelList.get(i).size()];
for (int j = 0; j < rs[i].length; j++) {
rs[i][j] = levelList.get(i).get(j).val;
}
}
return rs;
}
}```

133 篇文章42 人订阅

0 条评论

## 相关文章

### LeetCode 543. Diameter of Binary Tree

Given a binary tree, you need to compute the length of the diameter of the tree....

1370

5199

### LeetCode 144. Binary Tree Preorder Traversal题目分析代码

Given a binary tree, return the preorder traversal of its nodes' values. For ex...

982

3353

2310

### 501.Find Mode in Binary Search Tree(Tree-Easy)

Given a binary search tree (BST) with duplicates, find all the mode(s) (the most...

2356

### LeetCode 783 & 530 Distance Between BST Nodes

Given a Binary Search Tree (BST) with the root node root, return the minimum dif...

1880

### (43) 剖析TreeMap / 计算机程序的思维逻辑

40节介绍了HashMap，我们提到，HashMap有一个重要局限，键值对之间没有特定的顺序，我们还提到，Map接口有另一个重要的实现类TreeMap，在Tre...

2148

### Java中Set集合是如何实现添加元素保证不重复的？

Java中Set集合是如何实现添加元素保证不重复的？ Set集合是一个无序的不可以重复的集合。今天来看一下为什么不可以重复。 Set是一个接口，最常用的实现类就...

3987

### Q100 Same Tree

Given two binary trees, write a function to check if they are the same or not. T...

3276