题目描述
从上往下打印出二叉树的每个节点,同层节点从左至右打印。
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701
解题想法
队列实现,保存左节点、右节点,然后按照先进先出的顺序打印
代码实现
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.Queue;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<Integer> PrintFromTopToBottom(TreeNode root) {
ArrayList<Integer> list = new ArrayList<>();
if(root == null){
return list;
}
Queue<TreeNode> queue = new LinkedList<>();
queue.add(root);
while(queue.size() > 0){
TreeNode node = queue.poll();
list.add(node.val);
if (node.left != null){
queue.add(node.left);
}
if (node.right != null){
queue.add(node.right);
}
}
return list;
}
}