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

 

思路:

// @Title: 彩灯装饰记录 II (彩灯装饰记录 II)
// @Author: qisiii
// @Date: 2022-02-21 12:44:40
// @Runtime: 2 ms
// @Memory: 41.3 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 static List<List<Integer>> levelOrder(TreeNode root) {
        LinkedBlockingQueue queue = new LinkedBlockingQueue();
        List<List<Integer>> result = new ArrayList<>();
        if (root==null){
            return result;
        }
        queue.offer(root);
        doTree(queue, result);
        return result;
    }

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