Update 二叉树相关.md

master
Omooo 4 years ago
parent a413e12a61
commit 407cb6b371
  1. 35
      blogs/Algorithm/剑指 Offer/二叉树相关.md

@ -325,3 +325,38 @@ class Solution {
}
```
#### [32 - III. 从上到下打印二叉树 III](https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-iii-lcof/)
```java
class Solution {
public List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
Deque<TreeNode> deque = new LinkedList<>();
deque.add(root);
while (!deque.isEmpty()) {
int l = deque.size();
List<Integer> list = new ArrayList<>(l);
for (int i = 0; i < l; i++) {
TreeNode node = deque.poll();
list.add(node.val);
if (node.left != null) {
deque.add(node.left);
}
if (node.right != null) {
deque.add(node.right);
}
}
if (res.size() % 2 == 1) {
Collections.reverse(list);
}
res.add(list);
}
return res;
}
}
```

Loading…
Cancel
Save