Print Binary Tree Top to Bottom 从上到下打印二叉树
从上到下按层打印二叉树,一层从左到右打印。
思路
使用queue完成对树的层序遍历
/**
* 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>> levelOrder(TreeNode root) {
List<List<Integer>> ans = new ArrayList<>();
if(root==null){
return ans;
}
LinkedList<TreeNode> queue = new LinkedList<TreeNode>();
queue.offer(root);
while(!queue.isEmpty()){
ArrayList<Integer> integers = new ArrayList<>();
int length = queue.size();
for (int i = 0; i < length ; i++) {
TreeNode node = queue.poll();
integers.add(node.val);
if(node.left!=null){
queue.offer(node.left);
}
if(node.right!=null){
queue.offer(node.right);
}
}
ans.add(integers);
}
return ans;
}
}
Tag
tree