102. 二叉树的层序遍历

2021-04-17  本文已影响0人  康大侠
层序遍历
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> totalList = new ArrayList<>();
        if (root == null) return totalList;
        List<Integer> subList = new ArrayList<>();
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        int levealSize = 1;
        while (!queue.isEmpty()) {
            TreeNode tmpNode = queue.poll();
            levealSize--;
            subList.add(tmpNode.val);

            if (tmpNode.left != null) {
                queue.offer(tmpNode.left);
            }

            if (tmpNode.right !=  null) {
                queue.offer(tmpNode.right);
            }

            if (levealSize == 0) {
                levealSize = queue.size();
                totalList.add(subList);
                subList = new ArrayList<>();
            }
        }
        return totalList;
    }
上一篇下一篇

猜你喜欢

热点阅读