diff --git a/blogs/Algorithm/剑指 Offer/二叉树相关.md b/blogs/Algorithm/剑指 Offer/二叉树相关.md index b4e060e..84ec5c6 100644 --- a/blogs/Algorithm/剑指 Offer/二叉树相关.md +++ b/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> levelOrder(TreeNode root) { + List> res = new ArrayList<>(); + if (root == null) { + return res; + } + Deque deque = new LinkedList<>(); + deque.add(root); + while (!deque.isEmpty()) { + int l = deque.size(); + List 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; + } +} +``` +