Update 二叉树相关.md

master
Omooo 4 years ago
parent dae23b1f9b
commit 68616209ea
  1. 32
      blogs/Algorithm/剑指 Offer/二叉树相关.md

@ -133,3 +133,35 @@ class Solution {
}
```
#### [32 - I. 从上到下打印二叉树](https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof/)
```java
class Solution {
public int[] levelOrder(TreeNode root) {
if (root == null) {
return new int[0];
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
List<Integer> list = new ArrayList<>();
while (!queue.isEmpty()) {
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null) {
queue.add(node.left);
}
if (node.right != null) {
queue.add(node.right);
}
}
int[] result = new int[list.size()];
int index = 0;
for (int i : list) {
result[index++] = i;
}
return result;
}
}
```

Loading…
Cancel
Save