https://www.acwing.com/problem/content/43/
今天写这题,bfs层序遍历去遍历,代码如下
java
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<List<Integer>> printFromTopToBottom(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
Queue<TreeNode> queue = new LinkedList<>();
Boolean isLeft = true;
queue.offer(root);
while(!queue.isEmpty()){
List<Integer> currentLevel = new ArrayList<>();
Integer size = queue.size();
for(int i = 0;i < size; i++) {
TreeNode node = queue.poll();
currentLevel.add(node.val);
if(node.left != null) {
queue.add(node.left);
}
if(node.right != null) {
queue.add(node.right);
}
}
if(!isLeft) {
Collections.reverse(currentLevel);
}
res.add(currentLevel);
isLeft = !isLeft;
}
return res;
}
}
本文作者:yowayimono
本文链接:
版权声明:本博客所有文章除特别声明外,均采用 BY-NC-SA 许可协议。转载请注明出处!