题目地址

思路:

  1. 属于二叉树的层序遍历

二叉树常见遍历方式:前序遍历,中序遍历,后序遍历,层序遍历等

  1. 层序遍历需要保证每层遍历的顺序性,每层节点的先后顺序。因此可以利用队列来保存每层节点的顺序性(这里需要记一下队列常用api,add(),poll(),peek())
/**
 * 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) {
        if (root == null) return new int[0];
        ArrayList<Integer> arrayList = new ArrayList<>();
        scanTree(root,arrayList);
        int len = arrayList.size();
        int[] nums = new int[len];
        for (int i = 0; i < len ;i ++) {
            nums[i] = arrayList.get(i);
        }
        return nums;
    }

    // 层序遍历
    public ArrayList scanTree(TreeNode node,ArrayList nums) {
        Queue<TreeNode> queue = new LinkedList();
        queue.add(node);
        while(!queue.isEmpty()){
            TreeNode tmp = queue.poll();
            nums.add(tmp.val);
            if(tmp.left != null) queue.add(tmp.left);
            if(tmp.right != null) queue.add(tmp.right);
        }
        return nums;
    }
}

Q.E.D.


每一个平凡的日常都是连续的奇迹