剑指offer14 JZ32 从上往下打印二叉树(层序遍历)
从上往下打印二叉树
https://www.nowcoder.com/practice/7fe2212963db4790b57431d9ed259701?tpId=13&tqId=23280&ru=%2Fpractice%2Fa9d0ecbacef9410ca97463e4a5c83be7&qru=%2Fta%2Fcoding-interviews%2Fquestion-ranking&sourceUrl=%2Fexam%2Foj%2Fta%3Fpage%3D1%26tpId%3D13%26type%3D13
- 将根节点入队
- 循环(条件队列不为空)
- 队列头元素出队
- 访问节点visit()自定义操作
- 将访问节点的左孩子入队 将右孩子入队。
import java.util.*;
/**
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> res=new ArrayList<>();//存储结果
if(root==null){
return res;
}
Queue<TreeNode> queue = new ArrayDeque<TreeNode>();
queue.offer(root);//根节点入队
while(!queue.isEmpty()){
TreeNode temp=queue.poll();//对头元素出队列
res.add(temp.val);
if(temp.left!=null){
queue.offer(temp.left); //访问完该节点 将他的左节点和右节点入队列
}
if(temp.right!=null){
queue.offer(temp.right);
}
}
return res;
}
}