题目描述
不分行从上往下打印二叉树
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<Integer> printFromTopToBottom(TreeNode root) {
//定义结果数组
List<Integer> result = new ArrayList<>();
if(root==null) return result;
//定义队列结构
Queue<TreeNode> que = new LinkedList<>();
que.offer(root);
//遍历队列 打印每一层节点的值
while(!que.isEmpty()) {
int size = que.size();
for(int i = 0; i < size; i++) {
TreeNode node = que.poll();
result.add(node.val);
if(node.left != null) que.offer(node.left);
if(node.right != null) que.offer(node.right);
}
}
return result;
}
}