JZ60：把二叉树打印成多行

http://www.nowcoder.com/practice/445c44d982d04483b04a54f298796288

### 解法1：增加两个TreeNode：last和nlast

• last：表示当前遍历层最右结点
• nlast：表示下一层最右结点

```public class Solution {
ArrayList<ArrayList<Integer> > Print(TreeNode pRoot) {
ArrayList<ArrayList<Integer>> list=new ArrayList<ArrayList<Integer>>();
if(pRoot==null){
return list;
}
TreeNode last=pRoot;
TreeNode nlast=pRoot;
ArrayList<Integer> res=new ArrayList<Integer>();
while(!queue.isEmpty()){
TreeNode tmp=queue.poll();

if(tmp.left!=null){
nlast=tmp.left;
}
if(tmp.right!=null){
nlast=tmp.right;
}
if(tmp==last){
last=nlast;
res=new ArrayList<Integer>();
}
}
return list;
}

}```

### 解法2：根据层次遍历的顺序，每一层都是从左到右的遍历输出，借助于一个队列。

```import java.util.ArrayList;
import java.util.Queue;
public class Solution {
public ArrayList<ArrayList<Integer>> levelOrder(TreeNode root) {
ArrayList<ArrayList<Integer>> result = new ArrayList<>();
if (root == null) {
return result;
}
Queue<TreeNode> queue = new LinkedList<>();
while(!queue.isEmpty()) {
ArrayList<Integer> list = new ArrayList<>();
int size = queue.size();
for (int i = 0; i < size; i++) {
TreeNode temp = queue.poll();
if (temp.left != null) {
}
if (temp.right != null) {
}
}
}
return result;
}
}```

2022-12-29 23:08

2022-12-07 23:43

2022-12-01 13:35

2022-12-14 15:52

2022-12-30 12:08

2022-12-23 19:49

2022-12-03 20:01

01-11 20:08

2022-12-23 14:45

2022-11-30 17:35

2022-12-05 22:31

2022-12-03 19:43

2022-12-20 17:21

2022-12-20 13:54