彩灯装饰记录 I (彩灯装饰记录 I)

 

思路:

// @Title: 彩灯装饰记录 I (彩灯装饰记录 I)
// @Author: qisiii
// @Date: 2022-02-21 12:49:39
// @Runtime: 2 ms
// @Memory: 41.4 MB
// @comment: 
// @flag: 
/**
 * 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) {
LinkedBlockingQueue queue = new LinkedBlockingQueue();
        List<Integer> result = new ArrayList<>();
        if (root==null){
            return new int[0];
        }
        queue.offer(root);
        doTree(queue, result);
        int[] r=new int[result.size()];
        int count=0;
        for(Integer i:result){
            r[count++]=i;
        }
        return r;
    }

    public static void doTree(Queue<TreeNode> queue, List list) {
        if (queue==null||queue.isEmpty()){
            return;
        }
        Queue<TreeNode> temp = new LinkedBlockingQueue();;
        while (!queue.isEmpty()) {
            TreeNode poll = queue.remove();
            if (poll==null){
                continue;
            }
            list.add(poll.val);
            if (poll.left!=null){
                temp.offer(poll.left);
            }
            if (poll.right!=null){
                temp.offer(poll.right);
            }
        }
        doTree(temp, list);
    }
}
Licensed under CC BY-NC-SA 4.0
最后更新于 2024-10-18