力扣练习004---二叉树的层次遍历(102)

题目描述:

https://leetcode-cn.com/problems/binary-tree-level-order-traversal/

给定一个二叉树,返回其按层次遍历的节点值。 (即逐层地,从左到右访问所有节点)。

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

3
/ \
9 20
/ \
15 7
返回其层次遍历结果:

[
[3],
[9,20],
[15,7]
]

题目分析:

分层遍历,和广度优先搜索的思想不谋而和,比较简单,数据结构使用队列,算法为BFS

Java代码:

    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }

        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(root);
        result.add(Collections.singletonList(root.val));
        while (!queue.isEmpty()) {
            int queueSize = queue.size();
            List<Integer> list = new ArrayList<>();
            for (int i = 0; i < queueSize; i++) {
                TreeNode node = queue.poll();
                if (node == null) {
                    continue;
                }

                if (node.left != null) {
                    list.add(node.left.val);
                    queue.offer(node.left);
                }
                if (node.right != null) {
                    list.add(node.right.val);
                    queue.offer(node.right);
                }
            }

            if (!list.isEmpty()) {
                result.add(list);
            }
        }

        return result;
    }

 

力扣运行结果:

 

posted @ 2020-03-14 10:18  光头用沙宣  阅读(161)  评论(0编辑  收藏  举报