剑指Offer:从上往下打印二叉树(层序遍历java版)

题目描述

从上往下打印出二叉树的每个节点,同层节点从左至右打印。

利用队列FIFO特性

创建一个队列,然后依次添加左、右子节点。从队列中取的时候,就相当于在每一层从左到右的取节点

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> list = new ArrayList<>();
        if(root==null)
            return list;
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        while(!queue.isEmpty()){
            root = queue.poll();
            if(root.left!=null){
                queue.offer(root.left);
            }
            if(root.right!=null){
                queue.offer(root.right);
            }
            list.add(root.val);
        }
        return list;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_43165002/article/details/93469853