剑指 Offer 32 - I. 从上到下打印二叉树

题目:
从上到下打印出二叉树的每个节点,同一层的节点按照从左到右的顺序打印。

例如:
给定二叉树: [3,9,20,null,null,15,7],

    3
   / \
  9  20
    /  \
   15   7

返回:

[3,9,20,15,7]

Reference:力扣(LeetCode),https://leetcode-cn.com/problems/cong-shang-dao-xia-da-yin-er-cha-shu-lcof

解答:

/**
 * Definition for a binary tree node.
 * public class TreeNode {
 *     int val;
 *     TreeNode left;
 *     TreeNode right;
 *     TreeNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] levelOrder(TreeNode root) {
        Queue queue = new LinkedList<>();
        ArrayList arr = new ArrayList<>();

        if (root == null){
            return new int[0];
        }
        queue.offer(root);
        //采用队列,先进先出,再将左右节点加入队列中,直到没有节点
        while (!queue.isEmpty()){
            TreeNode temp = queue.poll();
            arr.add(temp.val);
            if(temp.left != null){
                queue.offer(temp.left);
            }
            if(temp.right != null){
                queue.offer(temp.right);
            }
        }
         //将ArrayList转换成Array
        int[] ans = new int[arr.size()];
        for (int i=0;i

你可能感兴趣的:(剑指 Offer 32 - I. 从上到下打印二叉树)