2019-11-02 12:07:41 +08:00
|
|
|
|
# 32.1 从上往下打印二叉树
|
|
|
|
|
|
|
|
|
|
[NowCoder](https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=11175&tPage=1&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking&from=cyc_github)
|
|
|
|
|
|
|
|
|
|
## 题目描述
|
|
|
|
|
|
|
|
|
|
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
|
|
|
|
|
|
|
|
|
|
例如,以下二叉树层次遍历的结果为:1,2,3,4,5,6,7
|
|
|
|
|
|
2019-12-05 01:47:57 +08:00
|
|
|
|
<div align="center"> <img src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/d5e838cf-d8a2-49af-90df-1b2a714ee676.jpg" width="250"/> </div><br>
|
2019-11-02 12:07:41 +08:00
|
|
|
|
|
|
|
|
|
## 解题思路
|
|
|
|
|
|
|
|
|
|
使用队列来进行层次遍历。
|
|
|
|
|
|
|
|
|
|
不需要使用两个队列分别存储当前层的节点和下一层的节点,因为在开始遍历一层的节点时,当前队列中的节点数就是当前层的节点数,只要控制遍历这么多节点数,就能保证这次遍历的都是当前层的节点。
|
|
|
|
|
|
|
|
|
|
```java
|
|
|
|
|
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
|
|
|
|
|
Queue<TreeNode> queue = new LinkedList<>();
|
|
|
|
|
ArrayList<Integer> ret = new ArrayList<>();
|
|
|
|
|
queue.add(root);
|
|
|
|
|
while (!queue.isEmpty()) {
|
|
|
|
|
int cnt = queue.size();
|
|
|
|
|
while (cnt-- > 0) {
|
|
|
|
|
TreeNode t = queue.poll();
|
|
|
|
|
if (t == null)
|
|
|
|
|
continue;
|
|
|
|
|
ret.add(t.val);
|
|
|
|
|
queue.add(t.left);
|
|
|
|
|
queue.add(t.right);
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return ret;
|
|
|
|
|
}
|
|
|
|
|
```
|
2019-11-02 14:39:13 +08:00
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2019-11-02 17:33:10 +08:00
|
|
|
|
<div align="center"><img width="320px" src="https://cs-notes-1256109796.cos.ap-guangzhou.myqcloud.com/githubio/公众号二维码-2.png"></img></div>
|